The observer pattern

What’s the problem?

I’m currently coding alot of Javascript for a project called Dogvibes. In short, it’s a music player based on libspotify and consists of Python server which provides media player APIs. To show the server functionality we needed a GUI, so I decided to make a HTML-based clone of the Spotify UI for starters.

Now, everyone that has tried to code a GUI knows that it quickly gets complicated with dependencies between different screen components. Basically, one of the ideas with the Dogvibes web-GUI is to have a data source which reflects the state of the server and components around it fetching this data. So, I was looking for a good way of handling “one-to-many” data promotion and I vaguely remembered something called the observer pattern. After some googling I found this article by IBM giving a good further reading on the topic. Feeling really inspired and optimistic after reading the article, I decided to give it a try in Javascript, despite having a thought in the back of my mind saying that this might be better of for languages without native support for events (like C++, used in the article example). However, as a C-programmer, I’ve always wanted to learn more on OOP and design patterns, and this seemed like a good opportunity.

Solution: the observer pattern?

The observer pattern is about having two types of components: a subject and one or many observers. The subject is the component that has data that the observers are interested in. Then when the subject updates this data, it will notify all the attached observers via an update-method, part of the observer-class.

A limitation with javascript is that it’s not really object oriented with stuff like inheritance/subclasses etc. so this has to be simulated. But for starters, lets define the subject and observer “base-classes”:

The subject class is pretty straight forward. It contains three methods and an internal array to keep track of all the observers attached to it. The methods are:

  • Attach – Will add an observer-object to the subject. Returns an ID handle to be used when detaching
  • Detach – Remove an observer from the subject based on the ID handle from the Attach-method
  • Notify – Invoke the callback/update-method on all observers to let them know that there is new data available in the subject

The observer class will not contain much code, but only a method that needs to be overriden by the class that will inherit from it.

Being concrete

The two classes above are quite simple and can’t really be of any use stand alone. So now we just need to build an application that could make use of them, ie. building a “concrete subject” and “concrete observers”. I decided to not make it hard for myself and implement a digital clock application, just as the example in the article.

First the concrete subject: a ClockTimer object which inherits the Subject class previously defined. Inheritance is simulated by first adding a reference to the Subject in the ClockTimer object, and then executing it during initialization. This will add all the members (Attach, Detach etc.) in the Subject-object to the ClockTimer-object aswell (see line 4 and 30 in the snippet below).

The ClockTimer will then keep track of the current time and automatically update and notify its observers every second. It also provides three methods for getting hours, minutes and seconds respectively. These will be used by the observer(s) to grab data with, once they have been notified.

Next, the concrete observer: a class which will attach to a subject provided by the user and display the current H:M:S time in an arbitrary DOM-container element. It inherits the Observer-class (using the same trick as for the ClockTimer object) and implements the Update-method, aswell as methods for starting and stopping the clock (Attaching and Detaching from the ClockTimer-subject, that is).

Ok, now we just need to tie it all together! Let’s start this darn thing:

Provided that there is an element with id=’DigitalClock’ in the HTML-code including this javascript, there should be a running clock somewhere in the browser! Fantastic! And the best part is that it’s super easy to add more clocks: just create more instances of the DigitalClock-class and you can have clocks all over the place!

Example code

The code in this post is quite complete, but a bit fragmented. It also lacks the appropriate HTML/CSS-code to be functional and attractive. So here’s a fully working demo of the concept:
http://sewa.se/code/javascript/observer/

Conclusion

So, is this any good? Did I learn something with this adventurous ride into OOP and design patterns? and more importantly, will I use this in the future?

Well, the way I see it, this solution makes things a little more complicated than it has to be in the Javascript world. Sure, I enjoyed diving into the observer pattern a bit more, but for the Dogvibes project and for future projects, I’ll probably stick to using events with jQuery. It’s really simple/straightforward and it solves the problem with “one to many”-notification elegantly (IMHO). It might not be entirely crisp from an interface point of view but something like this would solve the same problem:

I’ll be happy to hear your ideas on this topic!