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

后端 未结 2 1582
孤街浪徒
孤街浪徒 2021-02-15 05:58

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 i

相关标签:
2条回答
  • 2021-02-15 06:21

    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.

    0 讨论(0)
  • 2021-02-15 06:27

    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

    0 讨论(0)
提交回复
热议问题