Note that there are some explanatory texts on larger screens.

plurals
  1. POBetter solution for nested Backbone.js collections
    primarykey
    data
    text
    <p>Many of my Backbone models often deal with nested models and collections, so far I'm using a combination of <code>defaults</code>, <code>parse</code> and <code>toJSON</code> manually to achieve nesting:</p> <pre><code>ACME.Supplier = Backbone.Model.extend({ defaults: function() { return { contacts: new ACME.Contacts(), tags: new ACME.Tags(), attachments: new ACME.Attachments() }; }, parse: function(res) { if (res.contacts) res.contacts = new ACME.Contacts(res.contacts); if (res.tags) res.tags = new ACME.Tags(res.tags); if (res.attachments) res.attachments = new ACME.Attachments(res.attachments); return res; } }); ACME.Tag = Backbone.Model.extend({ toJSON: function() { return _.pick(this.attributes, 'id', 'name', 'type'); } }); </code></pre> <p>I've looked at a few plugins out there that basically does the same as above but with a lot less control and more boilerplate, so I'm wondering if anyone has a more elegant solution to this common Backbone.js problem.</p> <hr> <p><strong>Edit:</strong> I ended up with the following approach:</p> <pre><code>ACME.Supplier = Backbone.Model.extend({ initialize: function(options) { this.tags = new ACME.Tags(options.tags); }, parse: function(res) { res.tags &amp;&amp; this.tags.reset(res.tags); return res; } }); ACME.Tag = Backbone.Model.extend({ toJSON: function() { return _.pick(this.attributes, 'id', 'name', 'type'); } }); </code></pre> <p>It is worth noting that later I discovered that you'll need to pass nested model/collection data from the constructor into the constructor of the nested model via the <code>options</code> object.</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.
 

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