1

http://arturadib.com/hello-backbonejs/docs/1.htmlのチュートリアルに従っています。

次のコード スニペットがあります。

(function($){
  var ListView = Backbone.View.extend({    
    el: $('body'), // attaches `this.el` to an existing element.
initialize(): Automatically called upon instantiation. Where you make all types of bindings, excluding UI events, such as clicks, etc.

    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 を実行する必要があるのはなぜですか。私の bindAll の理解は、 render が呼び出されたときに this のコンテキストを使用できるようにすることです。

this.render() を呼び出しているので、コンテキストは既に this ではありません...なぜそうする必要があるのbindAllでしょうか?

4

1 に答える 1

1

このコードではbindAll、'render' は確かに冗長です。しかしrender、他のコンテキスト (特にコールバックとして) で呼び出されると便利です。

于 2013-02-15T13:29:38.057 に答える