M.dev()

Observer pattern

Observer pattern

28.02.2022

Javascript

What is Observer Pattern?

It offers subscription model, where functions (objects) get notified, when the event occurs, This promotes loose coupling, because the subscribers does not have direct knowledge of each other.

Example:

1const observer = () => { 2 let subscribers = []; 3 return { 4 subscribe: (fn) => subscribers.push(fn), 5 unsubscribe: (fn) => (subscribers = subscribers.filter((subscriber) => subscriber !== fn)), 6 notify: () => subscribers.forEach((subscriber) => subscriber()), 7 }; 8}; 9 10const ob = observer(); 11 12const notifyMe = () => console.log('Notified me'); 13 14ob.subscribe(notifyMe); 15 16ob.notify();

What if your functions need aditional params ? Just bind them!

1const observer = () => { 2 let subscribers = []; 3 return { 4 subscribe: (fn) => subscribers.push(fn), 5 unsubscribe: (fn) => (subscribers = subscribers.filter((subscriber) => subscriber !== fn)), 6 notify: () => subscribers.forEach((subscriber) => subscriber()), 7 }; 8}; 9 10const ob = observer(); 11 12const notifyMe = (name) => 'Hello ' + name; 13 14ob.subscribe(notifyMe.bind(this, 'Pijo')); //bind what we need before subscribing 15 16ob.notify();

Observer pattern is a powerful and clean approach for all tasks - from basic to very complex ones. It has many applications like handling state or DOM events, basically everything you can think of, that has some kind of event and something that needs to know about it.