2012-07-06 212 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; 
}