Last Updated: February 25, 2016
·
1.69K
· 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/

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside