为了将我的主干模型映射到我从服务器获得的内容,我使用了 GroupOn Dev 博客上描述的技术:https://engineering.groupon.com/2012/javascript/extending-backbone-js-to-map-rough-api-responses-into-beautiful-client-side-models/
但是,这仅将传入数据映射到模型。
我希望这是双向的,这样当我保存模型时,它会准备模型属性以匹配服务器模型。
准备模型输出的最佳解决方案是什么?
最佳答案
我遇到了完全相同的问题,我的服务器响应与我能够发布的完全不同。我在 Backbone.sync 对象的机制中发现了一种方法,可以在 Backbone.sync 中的以下语句中将自定义 JSON 对象发布到我的服务器:
if (!options.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model.toJSON());
}
sync 评估 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。然后您可以从 View 或 Controller 调用保存,如下所示:
getReversedMapping : function() {
ver reversedMap = {};
...
return reversedMap;
},
saveToServer : function() {
this._model.save(this.getReverseMapping, {
success : function(model, response) {
...
},
error : function(model, response) {
...
}
})
}
由于您覆盖的保存会自动将您传入的 JSON 复制到 options.data,因此 Backbone.sync 将使用它来发布。
关于javascript - Backbone 数据映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11780659/