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 m
Set options.attrs will allow you customise api param:
var model = new Backbone.Model();
model.save(null, {
wait: true,
success: function() {
},
attrs: _.omit(model.attributes, 'selected')
});
In fact there is a much simpler way of achieving this without messing with backbone save or sync function since you would no be expecting this behaviour to be permanent
if you look at backbone.js line 1145 you will see that
// Ensure that we have the appropriate request data.
if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
params.contentType = 'application/json';
params.data = JSON.stringify(options.attrs || model.toJSON(options));
}
Which means that you may override the data part of the xhr by putting data in your options
Since backbone save requires model.save([attributes], [options])
But remember that attributes like id might be essential to proper saving
Example
model.save( {}, { data: JSON.stringify(data) } ) ;
So you should be doing something like this
var data = { id : model.id , otherAttributes : 'value' } ;
model.save( {}, { data : JSON.stringify(data) } );
This do the trick quite well for me and could be used with any backbone with xhr such as fetch, save, delete, ...
If it is a one-off occasion, you could use mode.unset('selected', { silent:true })
(silent is set only to avoid firing the change event), to remove the attribute... This has the not so nice counter-effect of having to re-set it after saving though.
This said, I totally endorse one of the solutions above. Moreover if this is something you need on a more regular basis.
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.
To set only desired values, use HTTP PATCH insead of HTTP POST. On the backbone side, just add a patch attribute to the save method:
entity.save(data,{patch:true})
Using save with this attribute, only fields passed as data
are sent to the server.