I’m confused by the code in the if (obj.attachEvent) {...} block. I found this example while looking at this page: http://codebits.glennjones.net/cheatsheet/javascript.htm#events
Anyway, can someone explain what the code is doing? I’m assuming that obj is a DOM element, type is the type of event (like click or hover), and fn is the callback function.
function addEvent(obj, type, fn) {
if (obj) {
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]);
} else {
obj.addEventListener(type, fn, false);
}
}
};
I always use the following code to do cross-browser event attachment (without jQuery). Is the above approach in any way better than what I do?
function attachEvent(element, type, fn) {
if (element.addEventListener) {
element.addEventListener(type, fn, false);
} else if (element.attachEvent) {
element.attachEvent('on' + type, fn);
}
};
As you know
attachEventis the function in Explorer and I am not sure what willthisrefer to when the function is invoked if we add listener like this. Needs to test this.But this code
adds one function to the object and calls the original listener function from that function. This ensures that inside the original listener function
thiswill refer to the object for which listener has been added. This is actually for old versions of explorer I think.