我遇到了这个完全相同的问题,其中我的服务器响应与我能够发布的完全不同。我的Backbone.sync的机制内发现的天体的方式,我可以张贴到我的服务器在下面的语句自定义JSON对象Backbone.sync:
if (!options.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model.toJSON());
}
同步评估是否options.data不存在然后将params.data设置为字符串化模型。 options.data检查将我关闭。如果存在,同步将使用该模型而不是模型。所以考虑到这一点,我重写了我的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;
}
//In order to set .data to be used by Backbone.sync
//both opts and attributes must be defined
if (opts && attributes) {
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);
}
那么,你如何在你的情况下使用它?基本上你要做的是创建一个反转映射并返回结果JSON的方法。然后,你可以调用保存从您的视图或控制器如下:
getReversedMapping : function() {
ver reversedMap = {};
...
return reversedMap;
},
saveToServer : function() {
this._model.save(this.getReverseMapping, {
success : function(model, response) {
...
},
error : function(model, response) {
...
}
})
}
因为你重写自动保存副本你传递给options.data的JSON,Backbone.sync将用它来发布。
扩展'save'方法不是一个好主意。如您所示,这需要您复制参数检查。此外,您还忽略了原始保存方法中的其他检查。看看我的答案,而不是使用'sync'。 – smhg 2013-08-04 15:36:24