Backbone.js で _.bindAll() を使用する必要があるのはいつですか? 質問する

Backbone.js で _.bindAll() を使用する必要があるのはいつですか? 質問する

私は backbone.js を学習していますが、これについて混乱しています。次のチュートリアルに従っています:http://arturadib.com/hello-backbonejs/ より

最初の例 (1.js) を見るとわかるように:

(function($){
  var ListView = Backbone.View.extend({    
    el: $('body'), // attaches `this.el` to an existing element.

    initialize: function(){
      _.bindAll(this, 'render'); // fixes loss of context for 'this' within methods

       this.render(); // not all views are self-rendering. This one is.
    },

    render: function(){
      $(this.el).append("<ul> <li>hello world</li> </ul>");
    }
  });

  var listView = new ListView();      
})(jQuery);

しかし、 という文をコメントアウトすると_.bindAll(this, 'render');、これはまだ機能します。 Google で検索したところ、bindAll()コンテキストを切り替えると の呼び出しがthis.render利用できなくなる可能性があるため、 メソッドが必要であると誰かが言っていました。 「コンテキスト」について混乱しています。 また、呼び出し ( ) が利用できなくなるのはいつなのかを誰か説明してもらえますかthis.render?

ベストアンサー1

あなたが挙げた例では_.bindAll(this, 'render');必要ありませんが、this他のコンテキストに変更できる可能性のあるコールバック関数がある場合は_bindAll()便利です。

例えば:

initialize: function(){
  _.bindAll(this, 'render', 'clickFunc');
},
events: {
   'click .someElement': 'clickFunc'
},
clickFunc: function(e) {
   /** If you remove the clickFunc from the list of events in bindAll, 
          'this' will refer to the element that invoked the event.

       Adding the clickFunc event in the _.bindAll, ensures that 'this' stays
          as the view.
   */
  this /** <-- our focal point */
}

おすすめ記事