Lordphartmore
Lordphartmore

Reputation: 51

Backbone.js .save() JSON response attribute issue

So my issue is this.

Using backbone to save something in a MYSQL Database.

When I call this.model.save() I am getting a very weird issue.

The model will save the JSON response as an object and will not update the new values instead.

So my attributes in development tools will look something like this.

attributes: Object

0: Object

ID: "4"

Name: "TEST"

Title: "MEOW"

Stuff: "1"

When: "2013-02-14 22:17:14"

The 0 should not be there. I did confirm that the json object is valid so I know that is not the issue here.

Upvotes: 0

Views: 440

Answers (1)

jevakallio
jevakallio

Reputation: 35920

It looks like your JSON response is actually an array with a single element, not an object.

The property 0 is created when Backbone calls model.set(response), which in turn copies all keys of the response object to the attributes hash. If an array is passed to set, this is what happens.

You should fix your server to respond with a raw object ({...}) instead of an array ([{...}]). If you're not able to change the server behaviour, you can override Model.parse to unwrap the response on the client:

var Model = Backbone.Model.extend({
  parse: function(response) {
    return _.isArray(response) ? response[0] : response;
  }
});

Upvotes: 1

Related Questions