addEvent() recoding contest entryEach time a function is registered with an event on a object, it is added to an array for that event. The array is created the first time a function is registered, and is added to the object using the event type as a key.
At the same time as the array is created, a raiseEvent function, whose job it is to call each of the functions in the array, is attached to the real event. Although the script can fall back to the traditional event registration method for attaching raiseEvent, it attempts first to use an advanced method to avoid it accidentally being overwritten by a foreign script.
raiseEvent is the only function directly attached to the event on the object. It first fixes a number of incompatibilities surrounding the event object and then calls the functions in it's array. To correct the 'this' reference inside the added functions, raiseEvent copies each function to a temporary property on the object before calling them.
removeEvent checks first for the existents of the array and then loops through each of it's items, and removes the matching function if found. Now that the function is no longer in the event array it will no longer be called by the raiseEvent function.
function addEvent(obj, evType, fn)
{
var fns = obj["__" + evType] || [];
if (!obj["__" + evType]) {
obj["__" + evType] = fns;
var raiseEvent = function(e) {
if (!e && window.event) {
e = window.event;
}
if (!e.target) {
e.target = e.srcElement;
}
if (!e.stopPropagation) {
e.stopPropagation = function() {
e.cancelBubble = true;
};
}
for (var f in fns) {
obj.__fn = fns[f];
obj.__fn(e);
}
obj.__fn = null;
};
if (obj.addEventListener) {
obj.addEventListener(evType, raiseEvent, false);
}
else if (obj.attachEvent) {
obj.attachEvent("on" + evType, raiseEvent);
}
else {
obj["on" + evType] = raiseEvent;
}
}
for (var f in fns) {
if (fns[f] == fn) {
return;
}
}
fns[fns.length] = fn;
}
function removeEvent(obj, evType, fn)
{
var fns = obj["__" + evType];
if (fns) {
for (var f in fns) {
if (fns[f] == fn) {
fns[f] = null;
return;
}
}
}
}
If you have any questions, or have spotted any bugs or improvements, feel feel free to email me.
James Newton-King <james.newtonking@gmail.com>