chris
chris

Reputation: 36957

Parsing the successful response of Backbone.create method

The api's I work with return an object like

{
  status:'success',
  data: [{
    id: '37r878',
    desc: 'foo',
    summary: 'bar',
    ts: 00000000,
    status: 'open'
  }],
  message: null
}

When I run the create() method in backbone I am passing it an object example

{
  desc: 'foo',
  summary: 'bar',
  ts: 00000000,
  status: 'new'
}

which triggers a POST expectedly to create the new data. The issue is, that when the API responds with the object I show up top, amd is added to what data I created the model with (shown below), as well as in the case of the status property it gets overwritten, by the responses value.

What I am trying to figure out is how to I bypass this automatic updating of the model with the response, or better yet how do I update it specifically with the responses data property instead of the whole response.

So my Model ends up looking like (which is undesired)

{
  desc: 'foo',
  summary: 'bar',
  ts: 00000000,
  status:'success',
  data: [{
    id: '37r878',
    desc: 'foo',
    summary: 'bar',
    ts: 00000000,
    status: 'open'
  }],
  message: null
}

Upvotes: 0

Views: 31

Answers (1)

nikoshr
nikoshr

Reputation: 33364

Use Model.parse when you want to alter how Backbone interprets what your server returns. Something like

var M = Backbone.Model.extend({
    parse: function (resp) {
        return resp.data[0];
    }
});

Upvotes: 1

Related Questions