only update certain model attributes using Backbone.js
-
24-10-2019 - |
문제
With Backbone, I'm trying to update and save to the server just one attribute:
currentUser.save({hide_explorer_tutorial: 'true'});
but I don't want to send all the other attributes. Some of them are actually the output of methods on the server-side and so they are not actually true attributes with setter functions.
Currently I'm using unset(attribute_name) to remove all the attributes that I don't want to update on the server. Problem is those attributes are then no longer available for local use.
Suggestions on how to only save certain attributes to the server?
해결책
As of Backbone 0.9.9
Just pass {patch:true}
to the save
function, like this:
currentUser.save({hide_explorer_tutorial: 'true'}, {patch:true});
From the documentation,
If instead, you'd only like the changed attributes to be sent to the server, call model.save(attrs, {patch: true}). You'll get an HTTP PATCH request to the server with just the passed-in attributes.
다른 팁
You can use toJSON on the model to do so.
toJSON : function(){
return {hide_explorer_tutorial: this.get("hide_explorer_tutorial")};
}
This will be the only attribute sent to the backend on save.
In fact there is a much simpler way of achieving this
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) } ) ;
For your particular case
var data = { id : currentUser.id , hide_explorer_tutorial: 'true' } ;
currentUser.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, ...
Thanks for voting
I guess this isn't currently possible: Backbone.js partial model update
There is a trick, if you do not set data
property but attrs
property on the options
argument, the request payload would be the attrs
property value instead of all the model attributes.
Note: This also works for model create actions (POST).
For your particular case:
var data = { hide_explorer_tutorial: 'true' };
currentUser.save(data, { attrs : data });
You can find more details from the backbone.js 1.33 source code (line 1405 - 1409):
// 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));
}