在我的骨幹應用程序,我有一個由幾個子模型作爲參數模型。更新骨幹子模型後取/保存
我把它定義這樣:
app.Models.Account = Backbone.Model.extend({
initialize : function() {
this.set({
info : new app.Models.Info(),
logins : new app.Collections.Logins(),
billing : new app.Models.Billing(),
});
}
});
的問題是獲取和保存時。當我取例如JSON響應包括用於 info
的對象,logins
陣列和用於billing
的對象。主幹自動將它們分配爲常規參數,這意味着子模型被一個簡單的對象覆蓋。
我目前的解決方案是重寫fetch
方法的模型,像這樣:
fetch: function(options) {
options = options ? _.clone(options) : {};
var model = this;
var success = options.success;
options.success = function(resp, status, xhr) {
resp = model.parse(resp, xhr);
model.get('info').set(resp.info);
model.get('logins').reset(resp.logins);
model.get('billing').set(resp.billing);
if (success) success(model, resp);
};
options.error = Backbone.wrapError(options.error, model, options);
return (this.sync || Backbone.sync).call(this, 'read', this, options);
}
然而這僅僅是獲取。並且由於在調用save()
方法時返回創建的模型的更新狀態,所以我還必須覆蓋save()
方法。
是否有解決這個問題有什麼好的方法?
也許覆蓋set()
方法可以工作,但是我擔心這將意味着我將開始偏離主幹代碼庫。
我也想過用解析方法,像這樣
parse : function (response) {
this.model.get('info').set(response.info);
response.info = this.model.get('info');
this.model.get('logins').reset(response.logins);
response.logins = this.model.get('logins')
this.model.get('billing').set(response.billing);
response.billing = this.model.get('billing');
return response;
}
這將創建一個到已經更新子模型的參考。
一個可能的警告的東西像'this.model.get( '信息')集(response.info)。 response.info = this.model.get('info');'是'x = m.get('p'); x.set(...); m.set('p',x)'不會觸發''change''事件(請參閱http://stackoverflow.com/a/13369672/479863的後半部分),我不確定這是否將會是你的'parse'問題。 –
如果我有事件綁定到子模型,我必須測試這將如何工作。無論哪種方式,我都可以在不改變父模型的事件的情況下生活,因爲它主要用於將所有東西組合在一起,併發出ajax請求(使用骨幹同步)。 – Daniel