Observer Design Pattern using Javascript

bvnkumar

Bvnkumar

Posted on March 27, 2023

Observer Design Pattern using Javascript

Design patterns are used to solve the specific problems in the software. Today we will be discussed about Observer Pattern in javascript.

Observer pattern is a software design pattern in which an object, called subject, maintains a list of its dependencies called observers and notify them automatically of any state changes.

For Example, In react if state changes then components will re-render accordingly. this process is similar to observer pattern functionality.

Below is the sample program for observer pattern.


function Subject(){
  this.obeservers=[];
}

Subject.prototype={
  add:function(fn){
    this.obeservers.push(fn)
  },
  remove:function(fn){
    this.obeservers=this.obeservers.filter(fun=>f!=fn)
  },
  notify:function(){
    this.obeservers.forEach(fun=>{
      fun.call()
    })
  }
}
function observer1(){
  console.log("in the observer1")
}
function observer2(){
  console.log("in the observer2")
}
const subject=new Subject();
subject.add(observer1);
subject.add(observer2);
subject.notify() // It will loop through all the observers.
Enter fullscreen mode Exit fullscreen mode

In the above example, we have created the Subject constructor function. And it has observers list property, add, delete and notify methods.

Observers: It will have no.of observers.
Add: It will add observers(functions) to that list.
Remove: this method will remove the function from the list based on its argument.
Notify: this will notify all the observers in the list.

Comments and suggestions are always welcome.

馃挅 馃挭 馃檯 馃毄
bvnkumar
Bvnkumar

Posted on March 27, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related