Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference the caller object ("this") using attachEvent

Using the method .attachEvent() in IE, how can I reference the caller object (the element that triggered the event) with this? In normal browsers, using .addEventListener, the var this points to the element, while in IE it points to the window object.

I need it to work with the following code:

var element = //the element, doesn't matter how it is obtained
element.addAnEvent = function(name, funct){
   if(element.addEventListener) // Works in NORMAL browsers...
   else if(element.attachEvent){
     element.attachEvent("on"+name, funct);
     //where the value of "this" in funct should point to "element"
   }
}

I just made that code up, it's not exactly the same as my code, but if it works with it then it works with me!

like image 607
JCOC611 Avatar asked Jan 04 '11 02:01

JCOC611


People also ask

What does this refer to in addEventListener?

Simply put, it just means you should have a property in the object called "handleEvent" , which points to the event handler function. The main difference here is, inside the function, this will refer to the object passed to the addEventListener .


1 Answers

From this quirksmode article with regard to attachEvent:

  1. Events always bubble, no capturing possibility.
  2. The event handling function is referenced, not copied, so the this keyword always refers to the window and is completely useless.

The result of these two weaknesses is that when an event bubbles up it is impossible to know which HTML element currently handles the event. I explain this problem more fully on the Event order page.

Since the Microsoft event adding model is only supported by Explorer 5 and higher on Windows, it cannot be used for cross–browser scripts. But even for Explorer–on–Windows only applications it’s best not to use it, since the bubbling problem can be quite nasty in complex applications.

I haven't tested it, but a possible workaround may be to wrap the handler in an anonymous function that calls your handler via funct.call().

else if(element.attachEvent){
   element.attachEvent("on"+name, function(){ funct.call( element ) });
}

My apologies for the untested solution. I don't like doing that, but can't easily get to IE right now.

like image 137
user113716 Avatar answered Oct 17 '22 14:10

user113716