Javascript 主干数据映射
为了将我的主干模型映射到我从服务器获得的内容,我使用了GroupOn Dev博客上描述的一种技术: 但是,这仅将传入数据映射到模型 我希望这是双向的,这样当我保存模型时,它会准备模型属性以匹配服务器模型Javascript 主干数据映射,javascript,model-view-controller,backbone.js,datamapper,Javascript,Model View Controller,Backbone.js,Datamapper,为了将我的主干模型映射到我从服务器获得的内容,我使用了GroupOn Dev博客上描述的一种技术: 但是,这仅将传入数据映射到模型 我希望这是双向的,这样当我保存模型时,它会准备模型属性以匹配服务器模型 准备模型输出的最佳解决方案是什么?我遇到了完全相同的问题,我的服务器响应与我能够发布的完全不同。我在Backbone.sync对象的机制中发现了一种方法,可以在Backbone.sync中的以下语句中将自定义JSON对象发布到我的服务器: if (!options.data &&
准备模型输出的最佳解决方案是什么?我遇到了完全相同的问题,我的服务器响应与我能够发布的完全不同。我在Backbone.sync对象的机制中发现了一种方法,可以在Backbone.sync中的以下语句中将自定义JSON对象发布到我的服务器:
if (!options.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model.toJSON());
}
如果options.data不存在,则进行同步计算,然后将params.data设置为字符串化模型。选项.数据检查使我无法访问。如果存在,sync将使用它而不是模型。因此,我重写了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。然后,您可以从视图或控制器中调用save,如下所示:
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将使用它进行post 布伦丹·德隆帕的答案是可行的,但它把事情复杂化了
不要在保存方法中执行此操作。您不想每次都复制这些参数检查(如果它们在主干网中发生了某种变化怎么办?)
相反,请按如下方式覆盖模型中的同步方法:
var MyModel = Backbone.Model.extend({
...,
sync: function (method, model, options) {
if (method === 'create' || method === 'update') {
// get data from model, manipulate and store in "data" variable
// ...
options.data = JSON.stringify(data);
options.contentType = 'application/json';
}
return Backbone.Model.prototype.sync.apply(this, arguments);
}
});
当您需要以服务器就绪格式“准备”数据时,仅此而已。扩展
save
方法不是一个好主意。如您所示,这要求您复制参数检查。此外,您还忽略了原始保存方法中的其他检查。请看我的答案,它使用了sync
。