Tuesday, July 29, 2008

Dojo publish subscribe

The dojotoolkit provides a powerful publish-subscribe event system. In fact, I have yet to see a javascript toolkit that offers this functionality.

In dojo, this system allows developers to write objects that can publish or broadcast events. You can also write objects that subscribe to events. The reason this is so powerful is that it allows you to write code that is maximally decoupled. What does maximally decoupled mean? It means that your separation of concerns is largely taken care of.

For example, suppose I have three components in my javascript application (yes, a javascript application), model, view, controller. In view, I have a dialog widget that I want to reuse in several cases. I don't want to create 25 dialog widgets that only have subtle differences. If this were the case, I would need to also create 25 different events for the OK action of the dialog.

Using the publish-subscribe pattern with dojo, I can pass a topic to the dialog when it is displayed. The dialog then only has one event. This event publishes the topic. Then, any objects that subscribe to the topic in model, view, or controller, can then fulfill their responsibilities.

Another reason to employ this dojo system in your javascript application is for extensibility considerations. Future components simply need to subscribe to the existing topics accordingly.