胡子 lambda 函数访问其视图实例"this"



胡子 lambda 函数是否可以访问其视图实例this

Backbone.View.extend ({
    initialize: function (options) {
        this.collection = options.collection  // large backbone.collection 
    },
    parseContent: function (){
        return function (id, render){
            //this.collection is undefined below
            return this.collection.get (render (id)).get ('stuff);
        }
    }
});

尝试在initialize ()内部_.bind (this.parseContent, this)this仍然在parseContent ()内携带模型上下文。

我目前的解决方法是将this.collection保存到我的应用程序根命名空间并从那里访问。想知道是否有一种更清洁的方法可以按照上述意图执行此操作?

感谢您的建议。

如果你要传递 parseContent 返回的函数,你应该

  1. 在返回该函数之前绑定该函数 _.bind
  2. 并在 initialize 中使用 _.bindAll 在每个实例上强制this parseContent

您的视图可以写为

Backbone.View.extend ({
    initialize: function (options) {
        _.bindAll(this, 'parseContent');
        // you don't need this.collection = options.collection
        // collection is part of the special variables handled By Backbone
    },
    parseContent: function (){
        var f = function (id, render){
            console.log(this.collection);
        }
        return _.bind(f, this);
    }
});

还有一个演示 http://jsfiddle.net/nikoshr/VNeR8/

最新更新