简体   繁体   中英

backbone.js updating a model whose attributes have been changed

In SQL you would use the UPDATE command to update a row, how do you update a model in SQL where it's attributes have been changed from say another JSON Object.

I would like to do this in such a way so that it only changes the attributes that have been changed and not the whole model, I have seen the model.changedAttributes() command, but not sure how to use this.

Thanks

Edit:

I have tried this:

//code to update model
usersCollection.fetch({
  success: function() {
    var getModel = usersCollection.where(checkIDJSON);
    //update that partcular attribute
    getModel.set('interest', 'rolling stones');
    console.log("Users:" + usersCollection.toJSON());
  }, error: function() {
    // something is wrong..
  }                     
}); 

It returns with an error, "undefined is not a function"

As I understand you would like to save data from the model to the server with RESTful service and don't want to send all the data of the model but only those attributes which have been changed only. For this purpose you should use patch method:

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

You may send only attrs in this case or

model.save({patch: true})

just attributes which have been changed (in this case attrs will be model.changedAttributes() )

From backbone 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.

I am working on this right now myself.

Your logic looks correct from the documentation. After your getModel.set('interest', 'rolling stones'); I would do

getModel.save(); //saves the model to the database (or whatever you have setup)
userCollection.reset(); // reloads the collection from the database (or whatever you have setup.

If are not using the Backbone.sync methods then in order for backbone to work well I'd recommend overriding these methods in your classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM