简体   繁体   English

如何将功能绑定到骨干路由器?

[英]How do I bind a function to a Backbone Router?

I am trying to bind my router to a method in my router. 我正在尝试将router绑定到router中的方法。 Here is the router : 这是router

define(function(require) {

  var Backbone = require('backbone');
  var User = require('models/user.model');

  var Router = Backbone.Router.extend({
    user: null,

    initialize: function() {
      _.bind(this.updateUser, this);
      Backbone.on('userAuthenticated', this.updateUser);

      this.user = new User();
      this.user.fetch();
    },

    updateUser: function() {
      debugger;
    }
  });

  return Router;
});

I am binding the method updateUser to my router . 我将方法updateUser绑定到我的router When the event userAuthenticated is triggered, then I want to run the code in updateUser . 触发事件userAuthenticated ,我想在updateUser运行代码。 The event gets thrown and the method gets called, but when I get into the updateUser method, my this is not the router like I expect, but the global object. 引发该事件并调用该方法,但是当我进入updateUser方法时, this不是我期望的router ,而是全局对象。 What am I doing wrong? 我究竟做错了什么?

I pointed out in a couple comments that _.bind() returns a new function, which your example doesn't assign to anything. 我在几条评论中指出_.bind()返回一个新函数,您的示例未将其分配给任何函数。 However, a simpler solution would be to use the optional third argument to on() : 但是,一个更简单的解决方案是对on()使用可选的第三个参数:

Backbone.on('userAuthenticated', this.updateUser, this);

Backbone documentation 骨干文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM