我什么时候需要在 Backbone.js 中使用 _.bindAll()? [英] When do I need to use _.bindAll() in Backbone.js?

查看:13
本文介绍了我什么时候需要在 Backbone.js 中使用 _.bindAll()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习backbone.js,对此感到困惑:我正在按照教程进行操作:http://arturadib.com/hello-backbonejs/

I am learning backbone.js, and feel confused on this: I am following the tutorial : http://arturadib.com/hello-backbonejs/

如您在第一个示例 (1.js) 中所见:

as you can see in the first example (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');,这仍然有效.我在谷歌搜索过,有人说 bindAll() 方法是必要的,因为如果我切换上下文,this.render 的调用可能不可用.我对上下文"感到困惑.当调用 (this.render) 不可用时,有人可以解释一下吗?

But if I comment out the sentence: _.bindAll(this, 'render');, this will still work. I have searched in google and someone said that the method bindAll() is necessary since if I switched my context, the calling of this.render may unavailable. I feel confused on the "context". and also could some one explain me when the calling (this.render) will unavailable?

推荐答案

对于你给出的例子 _.bindAll(this, 'render'); 不是必需的,但如果你有回调函数,其中 this 可以更改为其他内容的上下文,然后 _bindAll() 可以很方便.

For the example you've given _.bindAll(this, 'render'); isn't necessary but if you have callback functions where this can possibly be changed to the context of something else, then _bindAll() can be handy.

例如:

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

这篇关于我什么时候需要在 Backbone.js 中使用 _.bindAll()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆