PATCH
モデルの属性をBackbone.jsに保存しながらリクエストを実行する正しい方法は何ですか?
3 に答える
{ patch: true }
Backbone.js v0.9.9以降、に渡すことができますsave()
。
続きを読む: http: //backbonejs.org/#changelog
James Cropchosの回答に加えて、以下を追加したいと思います。これは私から数時間を盗み、おそらく他の誰かを助けるからです。
James Cropchosの回答に記載されているように、バックボーンv.0.9.9model.save(attributesToPatchObject,{patch: true})
以降で可能なように使用する場合、最後の呼び出し以降に変更された属性を判別する方法を疑問に思うかもしれません。最近モデルを保存しませんでした)。model.save()
attributesToPatchObject
model.save()
model.fetch()
バックボーン自体はそれらの属性を追跡しませんでした。私はこの方法model.changedAttributes()
が適合すると思いましたが、backbone-docが言うように、この方法は
最後のセット以降に変更されたモデルの属性のみのハッシュ。存在しない場合はfalse
したがって、この方法はこのニーズに適合しませんでした。いくつかの調査の結果、バックボーン自体が保存されていない属性を追跡していないことがわかりました(ドキュメントをもっと注意深く読んだ場合、見事な発見ではありません)。
バックボーン.trackitは、モデルにメソッドを追加することで、必要な機能をバックボーンに正確に追加するバックボーンプラグインであることがわかりました。unsavedAttributes()
backback.trackitのドキュメントには、この方法について書かれています。
Backboneのmodel.changedAttributes()と対称ですが、最後の保存以降に変更されたモデルの属性のハッシュを返すか、存在しない場合はfalseを返します。changedAttributesと同様に、外部属性ハッシュを渡して、モデルとは異なるそのハッシュ内の属性を返すことができます。
それはこのように動作します:
//fetch an existing model from server
model.fetch({
success : function(model, respose, options) {
//tell backbone.trackit to track unsaved Attributes
model.startTracking();
}
});
//now some changes to the model happen
model.set("someProperty", "someValue");
/* save the model to server using the PATCH-Method
and only send the unsaved Attributes;
in this case only "someProperty" is sent
*/
model.save(model.unsavedAttributes(), {patch: true});
Since the unsavedAttributes()
returns false if there are no unsaved Attributes, you could additionally wrap your save()
statement within an if-condition which checks if unsavedAttributes()
returns something other then false and only do your PATCH-Request if it's needed (because something changed).
NOTE: You didn't have to call fetch()
to use startTracking()
so you can use this method even with newly created models (model.isNew()
returns true on that model), if there is a usecase for that.
Hopes this may save someone a little bit of research time.
Backbone.sync
既存のメソッドマッパーをオーバーライドして拡張する必要があります
var methodMap = {
'create': 'POST',
'update': 'PUT',
'delete': 'DELETE',
'read': 'GET',
'patch': 'PATCH'
};
次のようなモデルで独自のパッチメソッドを作成する必要があります
Backbone.Model.prototype.patch = function(options)
{
// some code here that checks what attributes have changed since last save
var xhr = (this.sync || Backbone.sync).call(this, 'patch', this, options);
return xhr;
}
Backboneをさらに拡張して含めることができ、必要に応じOPTIONS
てHEAD
ただし、jQueryがPATCH、OPTIONS、およびHEADメソッドをサポートしている場合でも、エンドユーザーのブラウザがサポートしていない可能性があることに注意してください。