gpt4 book ai didi

javascript - Backbone : Customise the model object before being sent/synced to the server

转载 作者:行者123 更新时间:2023-12-03 10:20:51 28 4
gpt4 key购买 nike

正在通过backbone提供的parse方法解析来自服务器的数据。

var the_model = Backbone.Model.extend({
parse: function(response) {
return {
id: ApiWrapper.getId(response.resource_uri),
resourceUri: response.resource_uri,
categoryId: response.alert_type_id,
latitude: response.latitude,
longitude: response.longitude,
utm: MapCoordinates.latLongToUTM(response.latitude, response.longitude),
categoryName: response.alert_type_name,
ranger: {
fullName: response.ranger_id.first_name + ' ' + response.ranger_id.last_name
},
icon: "/images/map-icons/map-alert-0" + response.alert_type_id + ".png",
dateTime: moment(response.time_stamp).format("dddd, MMMM Do YYYY, h:mm:ss a")
}
}
});

var collection = Backbone.Collection.extend({
model: the_model
parse: function(data_from_server) {
return data_from_server.results
}
})

为了将任何新添加的数据同步回服务器 - 由于服务器不会接受解析的格式主干仍然存在 - 我将如何处理?在同步到服务器之前,实际取消解析数据或重新格式化模型。

最佳答案

要控制模型将数据发送回服务器的方式,请覆盖 Model.sync并在选项中设置 attrs 属性:

var the_model = Backbone.Model.extend({
parse: function(response) {
// ...
},

sync: function(method, model, options) {
options = options || {};

if ((method==='create') || (method==='update')) {
// prepare the data you want to send
var data = {
resource_uri: this.get('resourceUri'),
alert_type_id: this.get('categoryId')
// other attributes you want to add
};

// pass that as an option to Backbone.sync
options.attrs = data;
}

return Backbone.Model.prototype.sync.call(this, method, model, options);
}
});

还有一个演示 http://jsfiddle.net/nikoshr/z31k1qtp/

关于javascript - Backbone : Customise the model object before being sent/synced to the server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29644681/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com