是的
绑定不需要访问视图实例的匿名函数:
this.listenTo(anotherModel, 'change:whatever', function() {
console.log('whatever changed!');
});
绑定需要通过 ECMAScript 的 function.bind 访问视图实例的匿名函数:
this.listenTo(anotherModel, 'change:whatever', function() {
this.$el.append('whatever changed');
}.bind(this)); //the .bind here is key!
...或者只传递第四个参数,Backbone 将为您绑定上下文
this.listenTo(anotherModel, 'change:whatever', function() {
this.$el.append('whatever changed');
}, this); //the this here is key!
对于它的价值,从技术上讲,您的普通骨干视图“方法”是一个匿名函数:
Backbone.View.extend({someMethod: function() {/*this function is anonymous technically*/}});
没关系。为了保持一致性,我总是将我的事件处理函数定义为视图方法,并且通常清楚地命名它们:
Backbone.View.extend({
events: {'click .start', 'onClickStart'},
initialize: function () {
this.listenTo(this.model, 'change', this.onChange);
},
onClickStart: function() {/*awesome code here*/},
onChange: function() {/*more awesome code here*/}
});
请注意,这也有助于可测试性。