JS Observer Pattern

Sead Alispahic
The Apps Team
Published in
2 min readDec 3, 2019

/*I had to learn NodeJS, because our team is using it and I need to be able to jump and fix stuff when stuff happens. So, one of main things NodeJS did to JS was introduction of events. I was looking at some videos explaining how those events work and I’ve realised, it is a bastardised observer pattern.

Observer pattern for those who are uninitiated is probably the most used pattern in the world today. Every click, every event, is probably processed using the observer pattern. The pattern was described in GoF “Design Patterns: Elements of Reusable Object-Oriented Software” back in 1994, but I am sure it was used way before. It was baked into JAVA, which was released in 1995.

The principle, also known as Hollywood principle (don’t call us, we will call you) works by observer patiently waiting for the call instead of querying constantly. Here is a sample code

*/

//we create an observer. In JavaScript there is no concept of Interface, so we have to agree on

//something (or use TypeScript). We agree that observer will have ‘observe(paramToObserve)’

//function implemented

class Observer{

constructor(observerPrefix){

this.observerPrefix = observerPrefix;

}

observe(paramToObserve){

console.log(this.observerPrefix + ‘ ‘ + paramToObserve);

}

}

//this is a second observer, to show that we just need to implement function

//and observer decides what to do with the call.

class AnotherObserver{

constructor(){

}

observe(paramToObserve){

console.log(‘You are not the boss of me’);

}

}

//this is a source object. For each event you want to have a separate list of

//event listeners. Node creates stuff on the fly, and then is using strings to distinguish.

class Source{

constructor(){

this.observers = [];

}

//we will iterate over the array to broadcast to all

//observers that something happened they were listening for

broadcast(toBroadcast){

for(var i=0; i<this.observers.length; i++){

this.observers[i].observe(toBroadcast);

}

}

//you want to be able to register observers obviously.

register(object){

this.observers.push(object);

}

//this is the main working method that will trigger event

//every time the count increases.

countTo(noToCount){

for(var i=0; i<=noToCount; i++){

this.broadcast(“counted to: “ + i );

}

}

}

//quick running of the program

//create observers

var o1 = new Observer(“first”);

var o2 = new AnotherObserver();

//create source

var src = new Source();

//register observers

src.register(o1);

src.register(o2);

//perform work

src.countTo(3);

//as before, to run the code, copy-paste the article

--

--