Created
July 21, 2011 18:14
-
-
Save fundon/1097794 to your computer and use it in GitHub Desktop.
Observer Design Pattern Using JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Notes: | |
Observer Event Pub/Sub | |
add → bind → subscribe | |
remove → unbind → unsubscribe | |
notify → trigger → publish | |
topic → type → topic | |
*/ | |
/** | |
* Observer Class | |
*/ | |
function Observer() { | |
this._observers = {}; | |
} | |
/** | |
* @param {Object} observer | |
* @param {String} topic | |
*/ | |
Observer.prototype.addObserver = function(observer, topic) { | |
if (!this._observers.hasOwnProperty(topic)) this._observers[topic] = []; | |
this._observers[topic].push(observer); | |
} | |
/** | |
* @param {Object} observer | |
* @param {String} topic | |
*/ | |
Observer.prototype.removeObserver = function(observer, topic) { | |
var topics = this._observers[topic] || [] | |
, l = topics.length | |
, i = 0; | |
for (; i < l; i++) { | |
if (topics[i] === observer) { | |
break; | |
} | |
} | |
this._observers[topic].splice(i, 1); | |
} | |
/** | |
* @param {Object} subject | |
* @param {String} topic | |
* @param {Object} data | |
*/ | |
Observer.prototype.notifyObserver = function(subject, topic, data) { | |
var topics = this._observers[topic] || [] | |
, l = topics.length | |
, i = 0 | |
, subject = subject || window; | |
for (; i < l; i++) { | |
topics[i].call(subject, data); | |
} | |
} | |
/** | |
* @param {String} topic | |
* @return {Array} | |
*/ | |
Observer.prototype.enumerateObservers = function(topic) { | |
return this._observers[topic] || []; | |
} | |
// Testing!!! | |
var o = new Observer(); | |
function f(e) { | |
console.log('O1: ' + e); | |
} | |
function g(e) { | |
console.log('03: ' + e); | |
} | |
o.addObserver(f, 'click'); | |
o.addObserver(function(e){ | |
console.log('O2: ' + e); | |
}, 'click'); | |
o.addObserver(g, 'click'); | |
var s = {}; | |
o.notifyObserver(s, 'click', 'hello world!'); | |
o.removeObserver(f, 'click'); | |
o.notifyObserver(s, 'click', 'WTF!'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment