同步时排除模型属性 (Backbone.js) [英] Exclude model properties when syncing (Backbone.js)

查看:28
本文介绍了同步时排除模型属性 (Backbone.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在我同步时从我的模型中排除某些属性?

Is there a way to exclude certain property from my model when I sync?

例如,我将有关某些视图状态的信息保留在我的模型中.假设我有一个选择器模块,这个模块只是在我的模型上切换一个 selected 属性.稍后,当我对我的集合调用 .save() 时,我想忽略 selected 的值并将其从同步到服务器中排除.

For example, I keep in my model information about some view state. Let's say I have a picker module and this module just toggle a selected attributes on my model. Later, when I call .save() on my collection, I'd want to ignore the value of selected and exclude it from the sync to the server.

是否有一种干净的方法?

Is there a clean way of doing so?

(如果您想了解更多详情,请告诉我)

推荐答案

这似乎是最好的解决方案(基于@nikoshr 引用的问题)

This seems like the best solution (based on @nikoshr referenced question)

Backbone.Model.extend({

    // Overwrite save function
    save: function(attrs, options) {
        options || (options = {});
        attrs || (attrs = _.clone(this.attributes));

        // Filter the data to send to the server
        delete attrs.selected;
        delete attrs.dontSync;

        options.data = JSON.stringify(attrs);

        // Proxy the call to the original save function
        return Backbone.Model.prototype.save.call(this, attrs, options);
    }
});

所以我们在模型实例上覆盖了保存函数,但我们只是过滤掉了我们不需要的数据,然后我们将其代理给父原型函数.

So we overwrite save function on the model instance, but we just filter out the data we don't need, and then we proxy that to the parent prototype function.

这篇关于同步时排除模型属性 (Backbone.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆