Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle custom response in Backbone model

I started integrating backbone in my project. The very first difficulty that i had was response from backend was not JSON Array or not designed for backbone. Here is an example.

//A backbone model
var Person = Backbone.Model.extend({});

// A backbone collection
var PersonCollection = Backbone.Collection.extend({  
  model : Person,  
  url: '/people'
});

So consider this, that when I request /people it does not return JSON array of people. Instead it return something like:

{header: "some str", people: ["person", "array", ".."], stats: "something is here" }

The problem with it is backbone is unable to assign this JSON response to models. Is there any tweak that can be done in controller on response. So accessing model can be normal. Any before/after hook.

FYI: backbone is getting response from server, I can see it under "responseText" key.

Any help is highly appreciated.

like image 870
ducktyped Avatar asked Jan 30 '12 10:01

ducktyped


1 Answers

Backbone supports this. I ran into the same issue when consuming data from Parse.com. In your case, when you have a /people endpoint that does not return an array, you can override the Collection.parse function to show Backbone how to find the array it is looking for:

var PersonCollection = Backbone.Collection.extend({
  model : Person,
  url: '/people',
  parse: function(resp, xhr) {
    this.header = resp.header;
    this.stats = resp.stats;
    return resp.people;
  }
});

If you need to do more in this function, then you should. In a similar way, you can override Model.sync if you need to.

like image 114
Brian Genisio Avatar answered Sep 18 '22 01:09

Brian Genisio