My REST api returns data in json in following format for `/api/users`:
{
"objects":[
{"User":{"id":"1","created":"2013-02-13 09:22:42","modified":"2013-02-13 09:22:42","username":"[email protected]","role":"admin"}},
{"User":{"id":"2","created":"2013-02-13 09:22:55","modified":"2013-02-13 09:22:55","username":"[email protected]","role":"analyst"}},
{"User":{"id":"3","created":"2013-02-13 09:23:02","modified":"2013-02-13 09:23:02","username":"[email protected]","role":"moderator"}},
{"User":{"id":"4","created":"2013-02-13 09:23:10","modified":"2013-02-13 09:23:10","username":"[email protected]","role":"representative"}}
],
"meta":
{"page":1,"pageCount":1,"prevPage":false,"nextPage":false,"limit":20,"count":4,"sort":null,"direction":null}
}
For /api/users/{id}
it returns data in following format:
{"User":{"id":"1","created":"2013-02-13 09:22:42","modified":"2013-02-13 09:22:42","username":"[email protected]","role":"admin"}
How I can integrate this with Backbone.js Collection and Model? I know Backbone.js expects api to return array of object dicts or pure object dict - is there a way to change it?
Yes, there is. You could override model.parse or collection.parse. For example:
var UserCollection = Backbone.Collection.extend({
model: User,
url: '/api/users',
parse: function(response) {
// process response.meta when necessary...
return response.objects;
});
}
});
var UserModel = Backbone.Model.extend({
//...
parse: function(response) {
return response.User;
});
}
});
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