Cross browser javascript events

/* ~~~~~~~~~ Event Functions ~~~~~~~~~ */

function hypEventDispatcher(){ this.events = []; }

//Add Event Listener
hypEventDispatcher.prototype.addEventlistener = function(event,callback){
this.events[event] = this.events[event] || [];
if(this.events[event]) this.events[event].push(callback);
}
//Remove Event Listener
hypEventDispatcher.prototype.removeEventlistener = function(event,callback){
if(this.events[event]){
var listeners = this.events[event];
for(var i = listeners.length-1; i>=0; --i ){
if(listeners[i] === callback){
listeners.splice(i,1);
return true;
}
}
}
return false;
}
//Dispatch Event
hypEventDispatcher.prototype.dispatch = function(event){
if(this.events[event]){
var listeners = this.events[event],len = listeners.length;
while(len--){ listeners[len](this); }
}
}
//Create Event Function - Use this as the event factory
function hypCreateEvent(eventName){
hypEventObject.prototype = new hypEventDispatcher();
hypEventObject.prototype.dispatchHypEvent = function(eventName){ this.dispatch(eventName); }
eventObject = new hypEventObject();
function hypEventObject(){ hypEventDispatcher.call(this); }
}

/* ~~~~~~~~~ Example Event ~~~~~~~~~ */

//Create Event
hypCreateEvent('hypevent');

//Add a Listener
eventObject.addEventlistener('hypevent',hypEventHandler);

//Event Handler
function hypEventHandler(){ alert('fired'); }

//Dispatch the event - this can be added anywhere in js or even in html onclick
eventObject.dispatchHypEvent('hypevent');

0 Comments

You must be logged in to post a comment.