はい
ビュー インスタンスへのアクセスを必要としない匿名関数をバインドします。
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!
...または単に 4 番目の引数を渡すだけで、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*/}
});
これはテスト容易性にも役立つことに注意してください。