0

では、次のようなモデルにイベント リスナーがあるとします。

this.listenTo(anotherModel, 'change:whatever', this.myMethod);

myMethod とは、非常にシンプルな 1 行のコード スニペットです。この状況で無名関数を使用したいのですが、それができないようです。

this.listenTo(anotherModel, 'change:whatever', function() {
  //The simplest code in the world
});

私に何ができる?それとも、オブジェクトが 1 行のメソッドでいっぱいになる運命にあるのでしょうか?

4

1 に答える 1

3

はい

ビュー インスタンスへのアクセスを必要としない匿名関数をバインドします。

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*/}
});

これはテスト容易性にも役立つことに注意してください。

于 2013-07-23T21:20:34.453 に答える