0

我有一个树状的主干模型,例如:

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",
});

addChildchildTree在初始化方法中添加的每个元素调用。但是在addChild方法内部,this指的是childTree集合而不是模型...我对javascript比较缺乏经验,对我来说根本没有意义...这是正确的行为,我该如何绑定监听器到模型里面addChild

JSON类似于:

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

提前致谢!

4

1 回答 1

3

尝试

childTree.on("add", _.bind(this.addChild, this));
于 2013-03-02T22:55:04.790 回答