小胡子lambda函数访问它的视图实例'这个'

时间:2013-09-17 07:49:32

标签: backbone.js mustache

小胡子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);
        }
    }
});

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

我目前的解决方法是将this.collection保存到我的应用根命名空间并从那里进行访问。想知道有没有一种更清洁的方法来实现上述目的?

感谢您的建议。

1 个答案:

答案 0 :(得分:1)

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

  1. 在使用_.bind
  2. 返回之前绑定该函数
  3. 并使用initialize中的_.bindAll在每个实例的this中强制parseContent
  4. 您的观点可以写成

    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/

相关问题