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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With