Search code examples
backbone.js

Can I save changed attributes of model after several set


I call set method multiple times and change several attributes. Then I want to send the changed data to the server with {patch: true}.

I can use model.save(attrs, {patch: true});, but I do not know attrs. I can't use model.toJSON() (unneeded fields) or model.changedAttributes() (only last set) to obtain attrs.

How can I do this?


Solution

  • According to changedAttributes:

    Optionally, an external attributes hash can be passed in, returning the attributes in that hash which differ from the model.

    So you could try caching the state of model using toJSON before you start modifying. Once your modifications are done, pass the new state to changedAttributes method to retrieve changed attributes hash and then send a patch request. Something like

    var oldAttrs = model.toJSON();
    
    // ...do modifications here
    
    var changedAttrs = model.changedAttributes(oldAttrs);
    dataTosend = model.pick(_.keys(changedAttrs));
    model.save(dataTosend, {patch: true});