Wednesday, September 24, 2008

Events


//will break if element.on[event] is modified directly elsewhere
//will break if the markup itself contains inline event listener functions ( <element onevent="function body"> )
//is incompatible with prototype library (Prototype library should not be used for ANY project.)

// using EVENT namespace ... could be different if needed, could possibly be Element.prototype ... could possibly be a jQuery extension/plugin (or incorporated into jQuery core?)

EVENT = {};

EVENT.elements = [];

EVENT.addListener = function(el, type, f, prepend){
    
    if(!el.eventListenerList){
        el.eventListenerList = [];
    }
    
    if(!el.eventListenerList[type]){
        el.eventListenerList[type] = [];
    }
    
    if(prepend){
        el.eventListenerList[type].splice(0,0,f);
    } else {
        el.eventListenerList[type].push(f);
    }
    
    if(!el['on'+type]){
        el['on'+type] = function(e){
            for(var i in el.eventListenerList[type]){
                el.eventListenerList[type][i](e);
            }
        };
    }
};

EVENT.removeListener = function(el, f){
    
    if(!el.eventListenerList){
        return;
    }
    
    //note: "var i in obj" is incompatible with icky prototype library
    var list = el.eventListenerList;
    for(var i in list){
        for(var j in list[i]){
            if( list[i][j] == f ){
                //remove it.
                el.eventListenerList[i].splice(j,1);
                return;
            }
        }
    }
    
};

EVENT.hasListener = function(el, f){

    if(!el.eventListenerList){
        return false;
    }
    
    //note: "var i in obj" is incompatible with icky prototype library
    var list = el.eventListenerList;
    for(var i in list){
        for(var j in list[i]){
            if( list[i][j] == f ){
                return true;
            }
        }
    }
    
    return false;
};

No comments:

Post a Comment