observer pattern

javascript design pattern

by kazu69

JavaScript

const Subscriber = function() {
  this.observers = [];

}

Subscriber.prototype = {
  subscribe: function(fn) {
    this.observers.push(fn);
    return this.observers;
  },
  unsubscribe: function(fn) {
    this.observers = this.observers.filter(v => {
      if (v != fn) return v;
    });

    return this.observers;
  },
  notify: function(data) {
    this.observers.forEach(fn => {
      fn.call(null, data);
    });
  }
}

const eventHandler = (string) => {
  console.log('Event:' + string);
}

const eventHandler2 = (string) => {
  console.log('Event2:' + string);
}

const s = new Subscriber();
s.subscribe(eventHandler);
s.notify('Hello');
s.subscribe(eventHandler2);
s.notify('Hello');
s.unsubscribe(eventHandler);
s.notify('Hello');