Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js Fetching a more complex data and using as a collection

Tags:

backbone.js

Assume I have a such json setting:

{
  page:1,   
  items:[
    {  
      name: 'item1', 
      id:1
    }, 
    {
      name: 'item1', 
      id:2
    }, 
    {
      name: 'item1', 
      id:3
    }
  ] 
}

And a such modelling:

var Item = Backbone.Model.extend({
    defaults: {name:  "No name"}
});

var ItemCollection = Backbone.Collection.extend({
    model: Item,
    url: '/some/ajax/url',
});

After fetching this json, how can I map the items set as the collection of the ItemCollection and add the page number as an attribute to the collection?

like image 493
Hellnar Avatar asked Apr 04 '12 22:04

Hellnar


2 Answers

As @asawyer mentioned, you have to override the parse method, but you don't need to actually instantiate each item, Backbone can do that for you if you return the array of items.

See the documentation for collection.parse

parse collection.parse(response)

parse is called by Backbone whenever a collection's models are returned by the server, in fetch. The function is passed the raw response object, and should return the array of model attributes to be added to the collection.

Your code could be written as

var ItemCollection = Backbone.Collection.extend({
    model: Item,
    url: '/some/ajax/url',

    parse: function(data) {
        this.page=data.page;
        return data.items;
    }
});
like image 77
nikoshr Avatar answered Oct 19 '22 10:10

nikoshr


You need to override parse

It will end up looking something like this:

class Item extends Backbone.Model
    defaults:
        name: "No name"

class ItemCollection extends Backbone.Collection
    model: Item
    url: '/some/ajax/url'
    parse: (data) ->
        items = []
        _.each data, (item) ->
            newItem = new Item
                id: item.id
                name: item.name
            items.push newitem
        items

(Coffeescript, but easy enough to convert to straight javascript)

Your other option is the relational plugin found at:

https://github.com/PaulUithol/Backbone-relational

I've never used it but it is supposed to do the parse mapping stuff for you I think.

like image 40
asawyer Avatar answered Oct 19 '22 10:10

asawyer