[英]How do I bind the my Router to my method - Backbonejs
I am trying to bind a method to my Backbone Router. 我正在尝试将方法绑定到我的Backbone路由器。 Here is my class: 这是我的班级:
define(function(require) {
'use strict';
var Backbone = require('backbone');
var Header = require('views/header.view');
var MainBody = require('views/main.body.view');
var Router = Backbone.Router.extend({
currentView: null,
routes: {
"about": "about"
},
initialize: function() {
Backbone.on('location', this.test);
debugger;
_.bindAll(this, 'test');
},
about: function() {
var header = new Header();
$('#header').html(header.render().el);
},
test: function(data) {
this.currentView.close();
}
});
return Router;
});
In the initialize block I am attempting to bind this
to test
. 在初始化块,我试图绑定this
来test
。 When I call the test
function, my this
is still Backbone
and not the current class. 当我调用test
函数时,我的this
仍然是Backbone
而不是当前的类。 What am I doing wrong and how do I fix this issue? 我做错了什么,如何解决这个问题?
You're binding it after you attach the handler. 附加处理程序后绑定它。
initialize: function() {
// `test` is bound with the wrong THIS
Backbone.on('location', this.test);
debugger;
// Here you actually do the binding
_.bindAll(this, 'test');
},
Just swap the order and see if that fixes your issue. 只需交换订单,看看是否能解决您的问题。
I think you need third parameter while calling Backbone.on 我认为你在调用Backbone.on时需要第三个参数
To supply a context value for this when the callback is invoked, pass the optional third argument:
model.on('change', this.render, this)
要在调用回调时为此提供上下文值,请传递可选的第三个参数:model.on('change', this.render, this)
Like this Backbone.on('location', this.test, this);
像这个Backbone.on('location', this.test, this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.