Events are the glue that binds web applications together. Users click on one thing, expecting that something else will happen. This cause/effect relationship is the key to understanding how to structure an advanced web application built on ExtJS or Sencha Touch.
I recently found a post on the Sencha forums by Doug Hendricks explaining the concept of a message bus. In short, the idea is to use an instance of Ext.util.Observable (Doug extends the class, creating a new UX) to push notifications to the subscribing components.
In recent months, I’ve found myself using this technique more and more… and the concept is so simple that it’s hard to believe more developers don’t use it.
Benefits of the Bus
One of the most important benefits of the message-bus approach is that your components can immediately lose external dependencies, reducing the application’s complexity and lowering code overhead.
For example, let’s look at the ExtJS 3.x Grid-to-Grid DnD example. If you open the source code, the example is fairly simple. Two grids are defined within the same scope, which makes assigning their DropTargets really easy.
However, in many applications these two grids will not be defined within the same scope. Furthermore, other components in the UI (e.g. a chart) may be affected by the addition or removal of records in each grid. If all three (potentially many more) of these components are not defined within the same scope, updating anything becomes a giant headache.
A Refined Example
Let’s illustrate this concept using a real-world example.
You’ll see that I have created two grids (DnD enabled), and a chart that displays the data contained in the second grid. Take a moment and drag some records from the first grid into the second – you’ll notice that the chart automatically updates itself. How does this happen*?
*This example uses ExtJS 3.x. In ExtJS 4.x, charts will automatically refresh themselves when their data stores detect a change. While this particular example doesn’t apply to ExtJS 4.x, the concept is still the same.
If you open the source code for my example, you’ll see that I define each component (two grids and a chart) in separate scopes so they are not aware of one another. However, the instance of Ext.util.Observable() is accessible to each of these components.
The concept is simple: components subscribe to an event on my aKa.msgBus object. Specifically, the chart in my example subscribes to (e.g. listens for) the “customEvent”. When that event fires, a new data store is pushed to the chart’s event handler; the new data store is then bound to the chart. ExtJS then does some magic to re-render my chart.
This is a simplified example, but you get the idea.