我正在学习骨架.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)吗?

最佳答案

对于该示例,您不必提供_.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 */
}

关于javascript - 什么时候需要在Backbone.js中使用_.bindAll()?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14513991/

10-12 07:03