不変のプロパティに投稿しようとすると、この正確な問題が発生しました。バックボーンモデルの問題は、デフォルトでは、すべてまたは何も投稿しないことです。ただし、部分的な更新を行うことはできます。これに対処するために、Backbone.Modelの子孫を作成し、model.saveを次のようにオーバーライドしました。
save : function(key, value, options) {
var attributes, opts;
//Need to use the same conditional that Backbone is using
//in its default save so that attributes and options
//are properly passed on to the prototype
if (_.isObject(key) || key == null) {
attributes = key;
opts = value;
} else {
attributes = {};
attributes[key] = value;
opts = options;
}
//Now check to see if a partial update was requested
//If so, then copy the passed attributes into options.data.
//This will be passed through to Backbone.sync. When sync
//sees that there's an options.data member, it'll use it instead of
//the standard attributes hash.
if (opts && opts.partialUpdate) {
opts["data"] = JSON.stringify(attributes);
opts["contentType"] = "application/json";
}
//Finally, make a call to the default save now that we've
//got all the details worked out.
return Backbone.Model.prototype.save.call(this, attributes, opts);
}
これにより、次のように、必要な属性をバックエンドに選択的に投稿できます。
//from the view - the GET may have delivered 20 fields to me, but I'm only interested
//in posting the two fields.
this.model.save({
field1 : field1Value,
field2 : field2Value
},{
partialUpdate : true
});
これが私の人生をとても楽にしてくれた方法をあなたに言うことはできません!それを考えると、changedAttributes()JSONを渡さない理由を尋ねる人もいるかもしれません。その理由は、場合によっては、変更された属性がクライアント側のみを対象としており、特にそのモデルも使用するビューへの変更を引き出すためです。
いずれにせよ、これを試してみてください...