Randomblue
Randomblue

Reputation: 116293

Saving only one attribute

I have a model for which I would like to save only the attribute title. This is what I have tried:

myBook.model.save(['title']);

The problem is that request.body is the whole myBook.toJSON() object, instead of just the relevant attribute title. Is that by design, or am I doing something stupid?

Upvotes: 0

Views: 904

Answers (1)

satchmorun
satchmorun

Reputation: 12477

It's by design.

save calls Backbone.sync to persist changes to your backend, which in turn does, among other things:

if (!params.data && model && (method == 'create' || method == 'update')) {
  params.contentType = 'application/json';
  params.data = JSON.stringify(model.toJSON()); // <-- jsonifies the entire model
}

There are plenty of ways to override this behavior. You can give your model a sync method, in which case it will be called instead of Backbone's default sync. Or you could just override Backbone.sync to do what you want.

However, most server-side frameworks will be able to handle receiving the full JSON object and only updating the changed content. Why do you need to only send the changed attribute to the server?

Side note: the first parameter to save should be a hash of attributes: so {title: newBookTitle} as opposed to ['title']. But I'm guessing that was probably just a quick example typo.

Upvotes: 2

Related Questions