Javascript这不是指骨干模型中的当前对象

时间:2013-03-02 22:50:08

标签: javascript backbone.js model scope this

我有一个树状骨干模型,如:

var Leaf = Backbone.Model.extend({
    urlRoot: "tests.json",
    initialize: function() {
        if (Array.isArray(this.get('children'))) {
            var childTree = new Tree();
            childTree.on("add",this.addChild);
            childTree.add(this.get('children'));
            this.set({children: childTree});
        }
    },


    addChild : function(child){
        console.log(this);console.log(child);
    },

});


var Tree = Backbone.Collection.extend({
    model: Leaf,
    url: "tests.json",
});
对于在初始化方法中添加到addChild的每个元素,都会调用

childTree。 但是在addChild方法中,this指的是childTree集合而不是模型...我对javascript相对缺乏经验,对我来说根本没有意义...这是正确的行为,我如何将监听器绑定到addChild内的模型?

JSON就像:

[{
    "name":"root",
    "children":[
        {
            "name":"inner",
            "children":[{
                "name":"innerinner",
                "attr":{"class":""},
                "checked":true,
                "locked":true,
                "children":[]
            }]
     }]
}]

提前致谢!

1 个答案:

答案 0 :(得分:3)

childTree.on("add", _.bind(this.addChild, this));