Search code examples
javascriptdesign-patternsdependency-injectioninstantiationgoogle-closure-library

Where would you instantiate nested components using Closure Library?


Closure library offers a basic life cycle for Components:

  1. Instantiation
  2. Rendering/Decoration
  3. Document Entering
  4. Document Exiting
  5. Disposal

I'm focusing on the first two. About design patterns, when is it better to instantiate a nested component in the first steps?

  1. Instantiation: needs to be hold on a property till added through addChild and consumes memory before necessary. Anyways, it allows to do some dependency injection or better initialization because of the parameters it receives.

  2. Rendering/Decorating: messes up the dom creation, which can be already complicated because of the references of other objects it needs. It also would need the instantiation parameters previously stored in some property. Anyways, holds the instantiation till is needed.

Maybe a separated method called after instantiation which wraps the rendering? I'm asking because Closure Libray book and documentation don't talk about this.


Solution

  • Doing some refactorying and trying to split logic, came to the following conclusion:

    The best option I've found so far is to create the components inside the createDom method:

    Normally, the parameters needed for components involve the data they present. My arquitecture uses DAO, which means all data objects are conveniently connected. Subcomponents usually need some other data objects which are accessible by the parent's DAO. Since the parent object is needing this DAO, it's ok to store it on a property for the use inside the createDom.

    The other thing is that instantiation and rendering in the createDom component, theoretically, only needs two lines, which isn't a mess.

    Again, it's the best possible solution to increase cohesion.