观察者模式

1.

function Publisher() {
  this.subscribers = [];
}

Publisher.prototype.deliver = function(data) {
  this.subscribers.forEach(
    function(fn) {
      fn(data);
    }
  );
  return this;
};

Function.prototype.subscribe = function(publisher) {
  var that = this;
  var alreadyExists = publisher.subscribers.some(
    function(el) {
      if ( el === that ) {
        return;
      }
    }
  );
  if ( !alreadyExists ) {
    publisher.subscribers.push(this);
  }
  return this;
};

Function.prototype.unsubscribe = function(publisher) {
  var that = this;
  publisher.subscribers = publisher.subscribers.filter(
    function(el) {
      if ( el !== that ) {
        return el;
      }
    }
  );
  return this;
};

var publisherObject = new Publisher;

var observerObject = function(data) {
  // process data
  console.log(data);
  // unsubscribe from this publisher
  arguments.callee.unsubscribe(publisherObject);
};

observerObject.subscribe(publisherObject);

2.

// example using listeners
var element = document.getElementById(‘a’);
var fn1 = function(e) {
  // handle click
};
var fn2 = function(e) {
  // do other stuff with click
};

addEvent(element, ‘click’, fn1);
addEvent(element, ‘click’, fn2);

 

posted @ 2013-02-22 11:30  瓦尔登湖的秋天  阅读(145)  评论(0编辑  收藏  举报