Search code examples
javascriptbackbone.js

How to send an extra data to the server using Backbone model save?


How to send extra data to the server in Backbone model.save()? I have seen some of examples on stack but it doesn`t work for me.

The only thing I `ve done is

this.model.save({
    mode: {
       change_all: 1                        
    }
});

but the 'mode' became the part of my model instead of being just extra data.

Can someone please explain me this?

And how to save only changed parameters? Save sends all model.


Solution

  • The easiest way:

    this.model.save({
      change_all: 1
    })
    

    This will send the model attributes as well as change_all: 1. Note that it will also set change_all: 1 as an attribute on the model.

    If that's undesired it's a little more complex, e.g. using jQuery ajax's data option:

    this.model.save(null, {
       contentType: 'application/json; charset=utf-8',
       data: JSON.stringify(_.extend({
            change_all: 1 
       }, this.model.attributes))
    })