考虑代码(也在 JSFiddle 上):
// Backbone calls this "view3"
InnerView = Backbone.View.extend({
initialize: function() {
this.parent = this.options.parent;
this.listenTo(
this.model,
"change:name",
function() { this.parent.onNameChange() }
);
}
});
// Backbone calls this "view2"
OuterView = Backbone.View.extend({
initialize: function() {
this.innerView = new InnerView({
model: this.model,
parent: this
});
},
onNameChange: function() {
console.log("'this' is bound to the outerview instance: " + (this.cid === "view2"));
}
});
var myModel = new Backbone.Model({ name: "foo" });
var outerView = new OuterView({ model: myModel });
// trigger onNameChange
myModel.set("name", "bar");
这将打印'this' is bound to the outerview instance: true
到控制台。但是,如果我将回调更改为:
this.listenTo(
this.model,
"change:name",
this.parent.onNameChange
);
(我在这个小提琴中完成了),然后我的控制台显示'this' is bound to the outerview instance: false
. 似乎它this
是绑定到InnerView
实例的。
为什么是这样?阅读listenTo 文档后,我希望this
始终绑定到一个InnerView
实例,因为listenTo
在内部调用InnerView
。