6

I've inherited a rather large Javascript/ExtJS3 code base, and there are many instances of invoking events inside of the overridden initComponent method, after the call to "...superclass.initComponent.apply(this, arguments)". Specific events are being invoked on specific objects in a manner such as the following:

this.filter.on('filterUpdated', function(filter, params)

I've started converting the code to use a pub/sub paradigm instead, to reduce the coupling between objects and their specific event names, but quickly ran into issues when publishing and/or subscribing to events within initComponent (which in ExtJS executes before rendering). I need to fire an "INIT" event from the highest level component when the screen first loads, and I was either getting an error (due to ExtJS "templates" not having been rendered as it turns out), or events not firing at all.

Then I read the following in the ExtJS source for Ext.Component (from which all components extend) and I had an "aha" moment:

    if (this.tpl) {
        if (!this.tpl.compile) {
            this.tpl = new Ext.XTemplate(this.tpl);
        }
        if (this.data) {
            this.tpl[this.tplWriteMode](contentTarget, this.data);
            delete this.data;
        }
    }
    this.afterRender(this.container);

When I switched to both publishing the "INIT" event from my topmost component's afterRender method, and subscribing to all events from all other components from their afterRender methods, everything worked as I expected. And now I am just wondering, largely to validate my design....

Is this a generally accepted way of implementing pub/sub in an event driven UI? Regardless of framework even? Namely are the following 2 good principles, or are their other ways?

  1. "Initialization events" should get published after all sub-components have rendered
  2. All sub-components should subscribe to all events (to be on the safe side) after they have rendered

Thanks in advance

Dexygen
  • 12,287
  • 13
  • 80
  • 147

1 Answers1

0

You have to balance the overhead of event handling vs. the possibility of missing significant events. In js/DOM land state is mutable.

For your #1 if you can identify a point in time when all your sub-components have rendered and subscribed, firing an init event makes sense.

For #2, it seems safe everyone to listen for events; however it could slow things down. If performance issues are apparent you may have to decide what events you don't care about and avoid subscribing.

seand
  • 5,168
  • 1
  • 24
  • 37