A Taste of Observer pattern in JavaScript
Observer pattern (also known as Pub/Sub pattern) can be used to help break down a whole application into more loosely coupled modules.
There would be an object (observer collection) maintains a list of events. Those observers (subscriber) will be automatically notified once the event occurs.
Code Sample:
observer subscribes to an event by the event name. ‘globalBroadcaster’ is an observer collection which stores the events subscribed. ‘handler’ is the action observer will make once the event occurs.
1 globalBroadcaster.subscribe('uniqueEventName', handler);Once the event be published, all the subscribers of this event will be notified. parameters could be injected when event published and it can be used by the subscribers. */
1 globalBroadcaster.publish('uniqueEventName', parameter1, parameter2, ...);Observer can unsubsribe the event in the ‘handler’ after being notified. In this case, observer won’t be notified if same event published again.
1 globalBroadcaster.unsubscribe('uniqueEventName', handler);
Conclusion
The biggest benifit of using Sub/Pub pattern comes from the concept of decoupling. Observer A doesn’t need to worry about how the event published or who announces the event, ‘A’ will process its handler once be notified.
The disadvantages also come from decoupling modules. It would be hard for one to draw a clearly workflow since some of the actions processed on the fly. It will cause chaos if not implemented properly.
Anyhow, I like the concept of decoupling, especially in group work.