Search code examples
javascriptjquerymodel-view-controllerbackbone.js

only update certain model attributes using Backbone.js


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?


Solution

  • 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.