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

标签 javascript backbone.js

正在通过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/

相关文章:

javascript - 设置特定大小后,Highcharts 图表在窗口调整大小事件上调整大小

JavaScript 不更新数组

javascript - 显示椭圆形黑球的 Canvas 弹跳球

backbone.js - Backbone JS 分页

javascript - 主干架构和 View 管理

javascript - backbone.js:从集合中删除后保留元素

javascript - 如何将送货地址详细信息传递给 token 、客户或收费对象?

javascript - 谷歌应用程序脚本使用触​​发器重新执行功能

javascript - jointjs:svg 文本在落到纸上时被空白替换

html - 如何使用 Handlebars 遍历 JSON 结构