Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Backbone Collection from a JSON API call that returns root parameters as well as array

Tags:

backbone.js

Backbone.js noob here.

I want to create a collection, from a JSON API external to my application. Specifically, the api from Stackoverflow. I know I should set the url parameter from a collection like this:

App.Collections.Users = Backbone.Collection.extend({
    model: User,
    url: "http://api.stackoverflow.com/1.1/users/800271;562692?jsonp=?&key=blahblah"
});

The problem is that the JSON API returns something like:

{
 "total": 2,
 "users": [
  {
   "user_id": 800271,
  },
  {
   "user_id": 800272,
  }
 ]
}
}

How do I ignore the "total" attribute?

like image 799
e3matheus Avatar asked Aug 13 '11 17:08

e3matheus


1 Answers

If this is the only collection in your app to work with such api, all you have to do is to override parse method for it:

App.Collections.Users = Backbone.Collection.extend({
    // ...
    parse: function(resp, xhr) {
        return resp.users
    }
})

If you also have to save your models, maybe you will need to override Backbone.sync. Don't hesitate to read backbone's source: it's thoroughly annotated and easy to follow.

like image 71
Georgii Ivankin Avatar answered Sep 27 '22 17:09

Georgii Ivankin