Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The "official" way is to override the parse method:</p> <p><a href="http://documentcloud.github.com/backbone/#Model-parse" rel="noreferrer">http://documentcloud.github.com/backbone/#Model-parse</a></p> <p>In your specific case, what I would probably do is, in the parse method, build the nested collection from the col1 data, delete it from the results, then hand the results on. Backbone will then turn the rest of the data into properties.</p> <p>I have not tried this, so I'm not 100% sure it works:</p> <pre><code>parse: function(response) { this.col1 = new NestedCollection(response.col1); delete response.col1 return response } </code></pre> <p><strong>Edit: Nov 28th 2012</strong></p> <p>Harm points out that this might not be the best way to do it any more. The original answer was written quite a while ago, and the original question indicated that the user wanted the collection to be a property on the model (not an attribute), but Harm has a point that having the collection as an attribute is a more accepted way of doing it these days. </p> <p>Today, you could use something like <a href="https://github.com/PaulUithol/Backbone-relational" rel="noreferrer">Backbone-Relational</a> to handle a lot of this stuff for you, or, if you wanted to do it yourself, and have the collection as a model attribute, you could do something like:</p> <pre><code>Building = Backbone.Model.extend({ parse: function(response) { console.log("Parse Called"); response.rooms = new Rooms(response.rooms); return response; } }); Room = Backbone.Model.extend({}); Rooms = Backbone.Collection.extend({ model: Room }); science_building = new Building(); science_building.fetch( {success: function(model,resp) {console.log(resp);}} ); </code></pre> <p>With a model fetch response like:</p> <pre><code>{ id: 1, name: "Einstein Hall", rooms: [ {id:101, name:'Chem Lab'}, {id:201, name:'Physics Lab'}, {id:205, name:'Bio Lab'} ] } </code></pre> <p>Resulting in a Building model that allows:</p> <pre><code>science_building.get('rooms').get(101).get('name') // ==&gt; "Chem Lab" </code></pre> <p>A working jsFiddle example: <a href="http://jsfiddle.net/edwardmsmith/9bksp/" rel="noreferrer">http://jsfiddle.net/edwardmsmith/9bksp/</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload