Skip to content

Design Pattern: Observer Method

fahimc edited this page Mar 10, 2013 · 1 revision

##Definition Allows objects to subscribe to an event.

###1. Create an Observer Class which will handle the subscribe, unsubscribe and on fire methods.

var Observer = function() {
	this.handlers = [];
	this.subscribe = function(eventName, callback) {
	if (!this.handlers[eventName])
	this.handlers[eventName] = [];
	this.handlers[eventName].push(callback);
	};

	this.unsubscribe = function(eventName, callback) {
	if (this.handlers[eventName]) {
	for (var a = 0; a < this.handlers[eventName].length; a++) {
	if (this.handlers[eventName][a] == callback) {
	delete this.handlers[eventName][a];
	a = this.handlers[eventName].length + 1;
	}

	}
	}
	};
	this.fire = function(eventName) {
	for (var a = 0; a < this.handlers[eventName].length; a++) {
	this.handlers[eventName][a]();
	}
	}
}

###2. Create a Class and attach a new Observer to it. Add a function which we will call when a 'click' event is fired.

var View = function() {
	this.observer = new Observer();
	this.clickHandler = function() {
	console.log("clicked");
	}
}

###3. Test Create an instance of the View Class and subscribe to a 'click' event and make it call the 'clickhandler' function when 'fire' is called. We will call 'fire' manually for this test.

var view = new View();
view.observer.subscribe("click", view.clickHandler);
view.observer.fire('click');
Clone this wiki locally