Return to Snippet

Revision: 1053
at September 5, 2006 08:52 by oronm


Initial Code
function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}

var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
addEvent(window,'unload',EventCache.flush);

Initial URL
http://www.dustindiaz.com/rock-solid-addevent/

Initial Description
In the aftermath of the addEvent() recoding contest, a winner was announced. It was also further discussed in the particleTree November issue with another method provided (I won’t discuss it since it’s copyrighted content and it’s for paying customers only ;) ). However even with all the fuss going on, I’ve taken an innovative approach with some existing methods and combined them into a very powerful function. It also accomplishes these three core issues.

    * Degrades on older browsers such as NS4 and IE5 mac
    * The this keyword remains in-tact
    * Avoids memory leaks in Microsoft Internet Explorer

Since none of this is entirely revolutionary or actually originally written by me, I’m not going to take any further credit other than piecing together what was already out there.
Introducing, my addEvent()

Here for your copy and pasting pleasure, it consists of three parts. 1) The addEvent() function itself which programatically adds to the 2) EventCache (originally written by Mark Wubben), and 3) an unload event is added to the window to run the EventCache ‘flush’ method.

Initial Title
Rock Solid addEvent

Initial Tags


Initial Language
JavaScript