Backbone.js/express.js parameters for model.save() Backbone.js/express.js parameters for model.save() express express

Backbone.js/express.js parameters for model.save()


As stated in Model.save documentation:

save model.save([attributes], [options])
[...] The attributes hash (as in set) should contain the attributes you'd like to change — keys that aren't mentioned won't be altered — but, a complete representation of the resource will be sent to the server.

You can however override the save method and provide a data attribute via the options which will be sent to the server instead of the full model representation. For example, this will only save the attributes passed to the method :

var M = Backbone.Model.extend({       save: function (attrs, options) {        options || (options = {});        options.contentType = 'application/json';        options.data = JSON.stringify(attrs);        Backbone.Model.prototype.save.call(this, attrs, options);    }});

And a Fiddle http://jsfiddle.net/dLFgD/


As @mikebridge noted in the comments, this behavior can now be obtained by passing an attrs option. So either use

book.save(null, {    attrs: {author: "Teddy"}});

or keep the override

var M = Backbone.Model.extend({    url: '/echo/json/',    save: function(attrs, options) {        options || (options = {});              options.attrs = attrs;        Backbone.Model.prototype.save.call(this, attrs, options);    }});

http://jsfiddle.net/nikoshr/dLFgD/7/


You could also send a PATCH request if you're using a Backbone version that supports it (>=0.9.9) and your server understands that verb, as explained in @pkyeck's answer


with the current version of Backbone (1.1.0) you could also do a PATCH which only sends the changed attributes to the server.

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.

taken from here: http://backbonejs.org/#Model-save

in your case this would be:

book.save("author", "Teddy", {patch: true});


The best way I have found to access POST parameters is to use the bodyParser middleware. This is referenced at this question: How to retrieve POST query parameters?

/* On startup, register the bodyParser middleware */app.use(express.bodyParser());/* Then, during route execution, each parameter can be accessed with req.param */app.post('/author/:id', function(req, res) {    var author = req.param('author', null); // Second parameter is default.  ...});