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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With