I want to call save
on a Backbone model and have it write data to the server, but not update the client. How do I do this?
To clarify: when Backbone saves a model, it sends all the data to the server, and then retrieves the data from the server and updates it on the client. This second step is what I want not to happen.
To clarify further: The model ('parent' model) has an attribute which is itself a model ('child' model); when it's saved to the server, this child model is converted to JSON. When the parent model updates after the save, the attribute that previously contained a reference to the child model is replaced with the parsed JSON object of the child model that was saved. This is what I need not to happen.
When the data is initially pulled from the server, the parent model "reconstitutes" that object into an appropriate child model, but this is an expensive process and there is no reason to re-do it every time save fires on the parent model, since the child model will never change.
Depending on how/what your server setup is, all you really have to do is issue a regular AJAX request. This is exactly what backbone does in the background so you'll just bypass the client side logic.
You could do this with native JavaScript, but I'm fairly sure you have some other library in use that can make things much easier.
For the completeness of this answer, I'll give an example with jQuery:
The
$.ajax
function also has some additional functionality, and you can read about it in the jQuery docs.It sounds like you do not want to
parse
your model when you receive the response from the server on amodel.save
You can try something such as:
You would have to set-up your parse function in your corresponding
model
as follows:Backbone currently defaults
options.parse
totrue
. Here is a short-discussion on the topic.As discussed in that thread, perhaps you want to consider why you do not want want to update the server response to the client. There may be a cleaner way to achieve the results you desire.
I ran into same problem.
model.save(attrs,{patch:true, parse:false})
really did not invoke parse method but model was still merged with server response.It is not elegant, but this worked for me:
I believe it's best to avoid this situation by clean REST api design.
On client you mean Views? If you want to save your model but not render your views which happens since
save
will trigger achange
event, you should callsave
with optionsilent:true
, or set a custom option likedontchange:true
when callingsave
and check it in when handlingchange
. I prefer the custom option, becausesilent
has side effects (at least in my version of backbone 1.0.0)a little code:
when you save:
you install your event listeners in the view: