Return to Snippet

Revision: 53037
at November 10, 2011 21:49 by magna


Updated Code
/** origin: http://blog.rvi-media.de/javascript/observer-in-javascript/
 */  
var Observer = function() {
	this.listeners = [];
	this.add = function(callback) {
		this.listeners.push(callback);
	};
	this.remove = function(callback) {
		/* TODO! ;) */
	};
	this.update = function(payload) {
		for (i in this.listeners)
			this.listeners[i](payload);
	};
};

var o = new Observer();
o.add(function(payload){document.writeln(payload);});
o.add(function(payload){alert(payload);});
o.update('foo');
o.update('bar');

Revision: 53036
at November 10, 2011 21:41 by magna


Initial Code
/** http://blog.rvi-media.de/javascript/observer-in-javascript/
 */  
var Observer = function() {	
	this.listeners = [];
	this.add = function(callback) {
		this.listeners.push(callback);
	};
	this.remove = function(callback) {
		/* TODO! ;) */
	};
	this.update = function() {
		var data = "hai!";
		for (i in this.listeners) {
			this.listeners[i](data);
		}
	};
};

var o = new Observer();
o.add(function(data){document.writeln(data);});
o.add(function(data){alert(data);});
o.update();

Initial URL
http://blog.rvi-media.de/javascript/observer-in-javascript/

Initial Description
Could be improved by passing an event instead of a simple payload.

Initial Title
Observer-Pattern in JavaScript

Initial Tags

                                

Initial Language
JavaScript