Search code examples
javascriptjsonbackbone.js

Common approach to fetch payload and meta data at one go in Backbone.JS?


What would be an elegant or 'idiomatic' way to fetch JSON data and get a single model and a collection from it, possibly all at one go.

{
   meta:  { 
             key: value, 
             key, value    /* This would be the single model */
          }, 
    data: [
            { /* record 1 */ }, 
            { /* record 2 */ }, 
            { /* record 3 */ }, 
            { /* record 4 */ } /* And so on. This would be the collection */
          ]

}

Or is the only option I have to fetch the raw JSON and create the model manually from response.meta, and the collection from response.data?


Solution

  • You can always override the parse method, for example:

    parse: function(response){
          return response['data'];
    }
    

    Ref: http://backbonejs.org/#Model-parse This will create the model using the attributes within "data".

    you are invited to see a dummy example iv'e just created:

    http://jsfiddle.net/5pjha/2890/