Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude model properties when syncing (Backbone.js)

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)

like image 477
Simon Boudrias Avatar asked Oct 24 '12 15:10

Simon Boudrias


2 Answers

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.

like image 143
Simon Boudrias Avatar answered Oct 09 '22 01:10

Simon Boudrias


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);     }, }); 
like image 29
byoungb Avatar answered Oct 09 '22 03:10

byoungb