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)
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
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
So you should be doing something like this
This do the trick quite well for me and could be used with any backbone with xhr such as fetch, save, delete, ...
I found some problems with the accepted solution, as options.data modifies the way Backbone makes the calls. Better using options.attrs as this:
my solution combine all the above. just use white list instead of black one .. this is good rule in general
define
and then overwrite the save
Having this same issue, I decided to create a small module that can help : https://github.com/lupugabriel1/backbone-model-save
This is how you can use it in your models:
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:
Using save with this attribute, only fields passed as
data
are sent to the server.Based on several of the answers, this accounts for cases of null objects and a conditional in Backbone that doesn't sent the
contentType
ifoptions.data
is already set: