考慮代碼(also on JSFiddle):爲什麼'this'不能與這個Backbone View保持一致?
// 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 fiddle所做的),那麼我的控制檯顯示'this' is bound to the outerview instance: false
。看來,this
被綁定到InnerView
實例。
這是爲什麼?在閱讀listenTo docs後,我認爲this
總是被綁定到InnerView
實例,因爲在InnerView
內調用了listenTo
。