私のバックボーンアプリケーションでは、パラメータとしていくつかのサブモデルからなるモデルがあります。フェッチ/セーブ後のバックボーンサブモデルの更新
私はそれを定義:
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( 'info')のようなものがある可能性のある警告が1つあります。set(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