Is there a way to exclude certain property from my model when I sync?
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?
(Let me know if you'd like more details)
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.
In Underscore 1.3.3 they added pick and in 1.4.0 they added omit which can be used very simply to override your model's toJSON
function to whitelist attributes with _.pick
or blacklist attributes with _.omit
.
And since toJSON
is used by the sync command for passing the data to the server I think this is a good solution as long as you do not want these fields wherever else you use toJSON
.
Backbone.Model.extend({ blacklist: ['selected',], toJSON: function(options) { return _.omit(this.attributes, this.blacklist); }, });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With