function cEvent(){
/**
* Private handlers
*/
var handlers = {};
* Adicionar tipo e manipulador * *
this.add = function(type, handler){
if(typeof handlers[type] === "undefined" ){
handlers[type] = [];
}
handlers[type].push(handler);
}
Tipo obrigatório de evento personalizado de incêndio no objeto
/**
* Fire custom event
* @param event Object
*/
this.fire = function(event){
if(!event.target){
event.target = this;
}
if( handlers[event.type] instanceof Array ){
var h = handlers[event.type], len = h.length, i;
for ( i=0; i < len; i++ ){
h[i](event);
}
}
}
Remover evento e manipulador *
/**
* Remove and event
* @param type string - name of event
* @param handler function
*/
this.remove = function(type, handler){
if( handlers[type] instanceof Array ){
var h = handlers[type], len = h.length, i;
for ( i=len-1; i > -1; i-- ){
if( handlers[i] === handler ){
break;
};
}
handlers.splice(i,1);
}
}
/**
* Return handlers
*/
this.getHandlers = function(){
return handlers;
}
};
Código de teste
var ev = new cEvent();
var counter = 0;
ev.add("message",function(e){
counter++;
e.element.innerHTML += "attached " + counter + " fire first<br />";
});
ev.add("message",function(e){
counter++;
e.element.innerHTML += "attached " + counter + " fire second<br />";
});
console.log( ev.getHandlers() );
window.addEventListener('load', function(e){
var d = document.getElementById("test");
var el = document.getElementById("message");
d.addEventListener('click',function(){
ev.fire({type : "message", element : el});
}, false)
}, false);
Você pode testar eventos personalizados em:
http://jsfiddle.net/F9phd/1/