lordfpx
5/26/2016 - 10:02 AM

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatic

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

// http://codepen.io/lordfpx/pen/xOKjbX?editors=0010

// http://www.dofactory.com/javascript/observer-design-pattern

function Click() {
  this.handlers = [];  // observers
}
 
Click.prototype = {
  subscribe: function(fn) {
    this.handlers.push(fn);
  },

  unsubscribe: function(fn) {
    this.handlers = this.handlers.filter(
      function(item) {
        if (item !== fn) return item;
      }
    );
  },

  fire: function(o, thisObj) {
    var scope = thisObj || window;
    this.handlers.forEach(function(item) {
      item.call(scope, o);
    });
  }
};

var elClick = document.querySelector('#click');
elClick.addEventListener('click', function(e){
  click.fire('event #1', e.currentTarget);
});

var clickHandler = function(data) {
  console.log(data);
};
 
var click = new Click();

click.subscribe(clickHandler);