javascriptinternet-explorerattachevent

What's the difference between these two addEvent functions?


This is the first:

function addEvent(el, type, fn){
    if(el.addEventListener){
        el.addEventListener(type, fn, false);
    }else{
        el[fn] = function(){
            fn.call(el, window.event);
        }
        el.attachEvent('on'+type, el[fn]);
    }
}

and the second:

function addEvent(el, type, fn){
    if(el.addEventListener){
        el.addEventListener(type, fn, false);
    }else{  
        el['e' + fn] = function(){
            fn.call(el, window.event);
        }
        el.attachEvent('on'+type, el['e'+fn]);
    }
}

the second one just add a prefix, what's it use for?


Solution

  • It looks to me like both functions try to do the same thing: bind event handlers in a way that is consistent across browsers (i.e., older IE versions that don't support .addEventListener()). If the .addEventListener() method is available it is used, otherwise it creates a proxy function that ensures the callback function is called with appropriate values for this and the event object.

    The difference is only in el[fn] versus el['e' + fn] when creating and later referencing a property on the element:

        el[fn] = function(){
            fn.call(el, window.event);
        }
    

    The fn parameter of addEvent() must be a function reference, and offhand I'm not certain what happens if you use a function reference as a property name but I would guess that it essentially does a toString() on the function and uses the result as the property name. So el['e' + fn] would do the same thing but add 'e' to the beginning. I don't see that the "e" has any special meaning.