Update only specific model attributes using Backbone.js

With Backbone, I try to update and save only one attribute to the server:

currentUser.save({hide_explorer_tutorial: 'true'});

but I do not want to send all other attributes. Some of them are actually server-side output methods, so they are not actually true attributes with setter functions.

I am currently using unset (attribute_name) to remove all attributes that I do not want to update on the server. The problem is that these attributes are no longer available for local use.

Suggestions on how to save only certain attributes on the server?

+3
source share
5 answers

Compared to base 0.9.9

{patch:true} save, :

currentUser.save({hide_explorer_tutorial: 'true'}, {patch:true});

,

, , model.save(attrs, {patch: true}). HTTP- PATCH .

+20

toJSON .

toJSON : function(){
  return {hide_explorer_tutorial: this.get("hide_explorer_tutorial")};
}

, .

+7

backbone.js 1145, ,

// 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));
    }

, xhr,

model.save([attributes], [options])

, , id,

model.save( {}, { data: JSON.stringify(data) } ) ; 

var data = { id : currentUser.id ,  hide_explorer_tutorial: 'true' }  ;  
currentUser.save( {}, { data : JSON.stringify(data) } );

xhr, , fetch, save, delete,...

+4
+1

, data attrs options, attrs .

: (POST).

:

var data = { hide_explorer_tutorial: 'true' };  
currentUser.save(data, { attrs : data });

backbone.js 1.33 ( 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));
}
0

All Articles