Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best pattern to have models listen to nested models and collections?

Using Backbone.js what is the best pattern to have models listen to all of their nested models and collections all the way down?

Should I put nested models/collections in attributes? Should I create parental relationships and trigger events manually?

like image 434
boom Avatar asked Oct 03 '11 23:10

boom


2 Answers

As with most things Backbone.js, you won't get a "right" answer to this, but I can share how I do it. With both models and views, I generally follow these guidelines:

  • Views and models should be instantiated by the component that's "responsible" for them. For models or views with clear parent/child relationships, the parent model should instantiate, usually in the initialize() method.

  • Parents should bind to child events at the time of instantiation.

  • Parents should be "aware" of children, and can call child methods if necessary - I'd usually use this method over triggering a child event, as it's more explicit. I try to keep children independent of their parents, communicating upwards through events. So yes, deeply nested models would communicate through event chains.

  • I sometimes .set() children as Backbone attributes, but usually just use plain Javascript attributes (e.g. this.child). It depends on the context. Using Backbone attributes provides change events, so if you need to monitor whether a child changes, use those. Backbone attributes also give you the ability to set at instantiation time, e.g. var myModel = new Model({ other: otherModel }) - but because parents usually instantiate their children, this doesn't really apply in that case, and I usually use that pattern for non-hierarchical model-model relationships. In most cases, I set children as plain Javascript attributes.

like image 147
nrabinowitz Avatar answered Nov 15 '22 14:11

nrabinowitz


I really like @nrabinowitz' answer. he covered all the right details.

just wanted to toss out the idea of using something like Backbone.Relational which handles all this stuff for you: https://github.com/PaulUithol/Backbone-relational

like image 20
Derick Bailey Avatar answered Nov 15 '22 15:11

Derick Bailey