我在尝试发布到不可变属性时遇到了这个确切的问题。Backbone 模型的问题在于,默认情况下,它们要么全部发布,要么不发布。但是您可以进行部分更新。为了解决这个问题,我创建了一个 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?原因是因为在某些情况下,更改的属性仅适用于客户端,特别是引发对也使用该模型的视图的更改。
无论如何,试试这个...