Here’s a cool pattern that I’ve been able to use in two of my projects lately:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
The method is based on jQuery’s
bind functions. These allow you to listen for a custom event on an element, and manually trigger an event on an element. This provides the basic backbone for the simple subscription model.
If an application element wants to subscribe to a topic, they bind a handler to the “subscription element”. This can be a designated element on the page, or just the window element. You can also of course use different elements for different subscriptions. Then, when something publishes to that topic, the handler function will execute.
For publishing, a function can pass a topic and parameters to the publish function. This calls jQuery’s
trigger to set off the event topic, passing along the parameters. These params are passed to the handle function.
If an element wants to cancel its subscription, they can pass the topic and handle function to the
unsubscribe method. Note that the handle has to be the same function object that was used to originally subscribe, not a copy or similar function. You also can use jQuery’s
unbind to cancel all subscriptions to a topic by only specifying the topic without the handle function.
I’ve found this to be a useful, lightweight way of creating loosely coupled messages across different components of my software systems.
- jQuery Documentation - in depth information on bind, trigger and unbind