无法理解backbone.js教程的例子

Car*_*Lee 0 javascript backbone.js underscore.js

我正在学习本教程之后的 backbone.js ,但是我遇到了解第一个例子的问题:

(function($){
  var ListView = Backbone.View.extend({
    ...
    initialize: function(){
      _.bindAll(this, 'render'); // fixes loss of context for 'this' within methods

       this.render(); // not all views are self-rendering. This one is.
    },
    ...
  });
  ...
 })(jQuery);
Run Code Online (Sandbox Code Playgroud)

Q1:为什么要使用(function($){})(jQuery); 而不是完美的工作(function(){})();

Q2:怎么_.bindAll(this, 'render')办?它如何修复方法中'this'的上下文丢失?

Zen*_*ter 8

Q1:通过将jquery作为参数传递给你自己2件事:

  1. 如果需要使用2个版本的jquery - 你准备好了
  2. 模块模式可能更好地被认为是封装良好且具有良好定义的依赖关系,因此通过声明jquery是一个参数 - 您声明了明确的依赖关系.当然还有其他方法(比如RequireJS),但这也是一种方法

Q2:bindAll是来自Underscore.js的实用方法,它绑定this特定方法 - 因此,当调用该方法(例如作为回调)时,this将在其中使用正确的方法.

例如:

(function($){
  var ListView = Backbone.View.extend({
    ...
    initialize: function(){
        // fixes loss of context for 'this' within methods
        _.bindAll(this, 'render', 'makestuff'); 

        this.render(); // not all views are self-rendering. This one is.
    },
    ...
    makestuff : function() { 
        ... 
        this.stuff = ... // some action on the list's instance
    }
  });
  ...
 })(jQuery);
Run Code Online (Sandbox Code Playgroud)

在你的代码的某些部分,你做了类似的事情:

var list = new ListView({...});
$('#button').on('click', list.makestuff);
Run Code Online (Sandbox Code Playgroud)

thisin makestuff方法是对上面的引用,list而不是on函数在其中makestuff实际调用时所处的任何上下文.

实际实现依赖于使用applycall函数将函数执行的上下文绑定到特定对象.