Skip to content

Instantly share code, notes, and snippets.

@leocavalcante
Created June 25, 2012 14:29
Show Gist options
  • Save leocavalcante/2988975 to your computer and use it in GitHub Desktop.
Save leocavalcante/2988975 to your computer and use it in GitHub Desktop.
javascript observer object
(function ( global, undefined ) {
var observer = {},
topics = {};
observer.on = function ( topic, fn ) {
if ( !topics[topic] ) topics[topic] = [];
topics[topic].push( fn );
return topics[topic].length - 1;
};
observer.trigger = function () {
var args = Array.prototype.slice.call( arguments ),
topic = args.shift();
if ( topics[topic] && topics[topic].length )
for ( var i = 0, l = topics[topic].length ; i < l ; i++ )
topics[topic][i].apply( null, args );
};
observer.off = function ( topic, index ) {
index === undefined ? delete topics[topic] : topics[topic].splice( index, 1 );
};
global.observer = global.observer || observer;
} ( this ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment