2012-07-06 124 views
1

。在UI更新的父级和子级模型上有一堆更改处理程序(以下简化版本)。我的问题是,一旦我打电话保存()父模型和JSON从服务器返回时,孩子模型数据更新,但它不再是公认的骨干机型,和我的处理程序全部失效。骨干JS - JSON响应公认我使用骨干与一些嵌套模型实际骨干模型

ChildModel = Backbone.Model.extend({ 
    defaults: { 
     property: "property"   
    } 
}); 

ParentModel = Backbone.Model.extend({ 
    defaults: { 
     childModel: new ChildModel()   
    }, 
    url : "resturl", 
    initialize: function() { 
     this.bind('change:childModel', this.changeHandler, this); 
    },    
    changeHandler: function() { 
     var child = this.get('childModel'); 
     if(child instanceof Backbone.Model){ 
     alert("is a backbone model"); 
     } else { 
     alert("is not a backbone model") 
     } 
    } 
}); 

var parent = new ParentModel(); 
parent.save() 

当调用parent.save()时,模型会被更新,但“不是骨干模型”会得到警报。

回答

0

考虑覆盖的解析方法和其他更新childModel了,而不是。方法。这适用于保存模型更新的绑定事件。

parse: function (response, xhr) { 
    // don't update the models childData attribute 
    if (this.get('childModel') instanceof ChildModel) { 

     this.get('childModel').set(response.childData); 
    } else { 
     this.set({ childModel: new childModel(response.childData); 
    } 
    delete response.childData; 
    return response; 
}