骨干和下划线js为什么我需要使用bindAll

时间:2013-02-15 13:23:47

标签: javascript backbone.js underscore.js

我正在关注以下教程: 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);

在initialize方法中,为什么我需要做bindAll。我对bindAll的理解是它允许在调用render时使用它的上下文。

因为我们正在调用this.render()不是上下文...为什么我们需要bindAll

1 个答案:

答案 0 :(得分:1)

在此代码中,“{”的bindAll确实是多余的。但是当在其他上下文中调用render时(尤其是作为回调),它很有用。