Skip to content

Instantly share code, notes, and snippets.

@fojas
Created August 6, 2010 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fojas/510851 to your computer and use it in GitHub Desktop.
Save fojas/510851 to your computer and use it in GitHub Desktop.
// listener object for attaching functions to be called after events
/**
* listener - Singleton. used to subscribe to and fire events
*/
var listener = function(){
/**
* @param {Object} evts the container for all event listeners
* @private
*/
var evts = {};
/**
* listen - subscribe to events
* @param {String} evtName the name to be listening for
* @param {Function} method the function to be fired
* @param {Object} context the value for the 'this' object inside the function
*/
var listen = function(evtName,method,scope) {
if(method && method.constructor == Function) {
evts[evtName] = evts[evtName]||[];
evts[evtName][evts[evtName].length] = {method:method,scope:scope};
}
};
/**
* fire - call all the event handlers
* @param {String} evtName the name of the event listner to invoke
* @param {Object} args args.data contains data passed to function,
* args.remove kills listener after it fires
*/
var fire = function(evtName,args) {
args = args || [];
if( evts.hasOwnProperty(evtName)) {
var evt = evts[evtName].reverse();
for(var i=evt.length;i--;) {
try{
evt[i].method.apply(evt[i].scope||[],(args.data||[]));
}catch(e){
if(args && args.data && args.data.push) {
evt[i].method(args.data[0]);
} else {
evt[i].method();
}
}
}
if(args.remove) {kill(evtName);}
}
};
/**
* listening - check if event is being listened for
* @param {String} evtName name of event to check on
*/
var listening = function(evtName){
return !!evts[evtName];
};
/**
* kill - stop listening to event
* @param {String} evtName name of event to kill
*/
var kill = function(evtName){
if(evts.hasOwnProperty(evtName)) {delete evts[evtName];}
};
// return the public functions
return {listen:listen,fire:fire,kill:kill,listening:listening};
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment