我什么时候需要在Backbone.js中使用_.bindAll()?

Ana*_*nar 22 javascript backbone.js

我正在学习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);
Run Code Online (Sandbox Code Playgroud)

但是,如果我评论出这句话:_.bindAll(this, 'render');这仍然有效.我在谷歌搜索过,有人说这个方法bindAll()是必要的,因为如果我切换我的上下文,调用this.render可能不可用.我对"背景"感到困惑.当call(this.render)不可用时,还有人可以解释一下吗?

Den*_*ngo 29

对于您给出的示例_.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 */
}
Run Code Online (Sandbox Code Playgroud)

  • 事件中的任何内容都由骨干,FYI自动绑定. (10认同)

Pet*_*ons 10

  • 在视图的事件哈希中列为属性值的任何方法都会由骨干自动绑定
  • 您可以手动绑定视图中手动用作模型或集合中的事件处理程序的任何方法 bindAll
    • 或者,您可以在注册绑定时提供上下文
    • 或者您可以使用EMCA 5的function.bind来获得相同的结果

片段:

events: {
    'click .win': 'win',
    'click .lose': 'lose'
},
initialize: function () {
    //win and lose are automatically bound for you
    //because they are in the events property

    //refresh must be manually bound
    this.model.on('change', this.refresh);

    //which you can do ECMA5 style if you like
    this.model.on('change', this.refresh.bind(this));

    //OR you can provide a context backbone style
    this.model.on('change:foo', this.fooChange, this);

    //However, since you pretty much never want an unbound function
    //in a view, you can just stick this in all your initialize methods
    //and call it done
    //Note this will bind all functions in your view class if you don't
    //pass specific method names. I recommend this form.
    _.bindAll(this);
},
win: function () {...},
lose: function () {...},
refresh: function () {...},
fooChange: function() {...}
Run Code Online (Sandbox Code Playgroud)

... OOOOORRRR只需使用CoffeeScript和胖箭头,并在语言级别干净利落地解决这个问题.

  • 我更喜欢_.bindAll(this),但是Underscore不推荐它,并且自1.5.0版本以后它将不再受支持.在更改日志中,您可以阅读:删除了在没有方法名称参数的情况下调用_.bindAll的功能.将你想要绑定的方法的名称列入白名单几乎总是更明智.http://underscorejs.org/#changelog我认为这是一个错误.维护起来会困难得多. (2认同)