DEV Community

Bvnkumar
Bvnkumar

Posted on • Edited on

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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay