AlgorithmsCodilityPatternsTutorials

Observer pattern is used everywhere, wheter jQuery’s .on() method, whether native addEventListener, whether flux dispatcher, some variant of observer pattern is implemented.

We can distinguish between two main variants, the “traditional” Observer pattern, later in text just Observer, and Publish/Subscribe.

The Observer pattern consists of two main parts, the subject( the object that we are observing ), and the observer( the object that asks the subject to be notified on change ).

The observer first registers a callback method on subject, and then when the subject performes the action observer registered to, it triggers that method. For example:

The example is pretty self explanatory, as it is obvious what happens. Steve, Dave and Jeff all said to pub to notify them when it is empty. Along with the object, we could have sent the method we wanted to be executed, but beware of “this” in Javascript, as depending on the context, it can have different behavior. There are four different behaviors if i’m not mistaken, but that’s material for another post ­čÖé

There are rare occasions where you will want to be doing this publish subscribe implementation manually, as there are many good libraries that implement this alongside the native javascript implementation. The most simple implementation is probably the native one, called Event emiter/Target/Dispatcher. All browsers implement these three methods

As you can see, the pattern is not that different from the first one, as we could add an event listener for all three of our guys, and all three would get notified. All DOM events are based on this paradigm.

Another slight variation is the Publish/Subscribe pattern, that utilizes a single centralized event aggregator that takes care of all the events. There are numerous advantages to this design, as it allows for complete decoupling of components allowing them to communicate through one single centralized object.

The caveat here is that the global broadcaster can get enormous pretty fast, and as it takes event types as strings, it can get pretty hard to debug.

The solution to that is called Signals, and instead of strings to identify types, it uses methods. That means that every event type has it’s own controller.

This allows for a more fine approach, but is not as common as the previous versions of this pattern.

There are numerous variants of the same idea, jQuery callbacks is a very interesting one, as it is used internally in deffereds and ajax. Angular 2 distinguishes asynchronous vs synchronous events, while Angular 1 had the $on and $emit methods, the possibilities are endless, so go ahead and try it out…