Last Updated: February 25, 2016
·
1.461K
· phantom

Javascript Custom events

function cEvent(){
    /**
     * Private handlers
     */
    var handlers = {};

*Add type and handler **

this.add = function(type, handler){

    if(typeof handlers[type] === "undefined" ){
        handlers[type] = [];
    }

    handlers[type].push(handler);
}

Fire custom event required type in object

/**
 * 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 event and handler*

    /**
     * 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;
    }
};

Test code

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);

You can test custom events on :
http://jsfiddle.net/F9phd/1/