JSFiddle - React, Tailwind, and code Playground
HTML
<div id="test">CLICK ME </div>
<div id="message"></div>
CSS
#test{ cursor: pointer; }
JavaScript
function cEvent(){
/**
* Private handlers
*/
var handlers = {};
this.add = function(type, handler){
if(typeof handlers[type] === "undefined" ){
handlers[type] = [];
}
handlers[type].push(handler);
}
/**
* 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);
}
}
}
/**
* 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;
}
};
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);