It’s time to introduce you guys to the Observer pattern. If you’ve been following this blog lately, you may have already had an introduction through my post talking about my jQuery plugin called JZ Publish/Subscribe. Well, here we’ll be talking about a few other ways to implement the Observer pattern, so you’ll know the method that works best for you and your application.
The Observer pattern is a pretty simple concept. An observer (aka subscriber) subscribes to an observable object (aka publisher), waiting for something of interest to happen. Observers are also able to unsubscribe from the observer. At this point the behavior is dependent upon the way you have implemented the pattern. There are two basic methods for observers to get information on what is going on: push and pull. In the push method, whenever something happens, the observable immediately notifies the observers of the event. In the pull method, the observer will check with the observable to see if anything has changed whenever the observer feels it necessary to check.
I’m betting you want to see an example. Of course you do! You’re a programmer and to you code makes more sense than plain English, right? Let’s start off with an example of the push method:
There are a few things to talk about here. First off, all the functions related to the observer pattern are implemented within
Now we’ll implement the pull method of the observer pattern. When you’re using the pull method, it makes more sense to swap things around a bit:
This is quite different from the push way of doing things, isn’t it? Now, whenever the observer feels like it should – or in this case, whenever I tell it to – it will check on the status of the observable(s) it is subscribed to. Normally this would be on a timer or something, but I decided to keep it simple and just call it manually. Once again
Observable in this code shouldn’t technically be used by itself. Instead it should be subclassed so that there are built in mechanisms that change the status, rather than manually changing it like I did in the example.
The examples I’ve given are very simple examples and generally an observable object can have more than one type of event to be observed. Speaking of events, you may or may not have realized that event handling on DOM elements is an implementation of the observer pattern. The observer pattern is everywhere and is quite powerful and useful. Also, many jQuery plugins that use animations will include the observer pattern so you can inject your own functionality into different points of an animation.
The observer pattern is a marvelous tool for maintaining and organizing large action-based applications or even just to make your jQuery plugin more accessible and flexible. It adds a nice level of abstraction to help decouple your code and keep it clean and maintainable. Obviously the observer pattern shouldn’t be used for everything, but it can be quite useful in innumerable situations.