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