Please note that ExpatTech no longer operates regular office hours, meeting is by appointment only. Please call +36306031104 for details.

ExpatTech Techblog

Nagy Richárd 2009.06.11. 16:58

About IE, the event handlers, and 'this'

Another beautiful evening I spent with IE.

Normally I use addEventListener/attachEvent (congratulations again, IE) to handle events, and normally I love it, and feel this is the way things should work. One day I ran into a problem, when in the event handler I needed a reference to the object I defined the event on. Consider this:

<div class="sokilyenvan" id="joskabacsi">
<img alt="" src="blah.gif" />
nyehehe
<span id="pistabacsi">gihi</span>
</div>

So, I attach an 'onclick' event to all the elements which are of the class 'sokilyenvan'. In the event handler, I need to know which specific one was clicked (for example 'joskabacsi'). In the event object, we have target/srcElement, which should return the reference to the object which fired the event. But if you attached the 'onclick' to the 'joskabacsi' DIV, it will of course also fire when you click the elements inside it (ex. the IMG). The IMG is 'above' the DIV, so when you click on the IMG, the event handler will run, but target/srcElement will have a reference to the IMG, not the DIV. And this is not a problem, because it should work this way. But in this case, I needed the object which the event was defined on. It did not seem to be a big wish.

In Firefox (and other 'normal' browsers) it is easy, when inside an event handler you write the 'this' keyword, it refers to the object on which you defined the event. Fantastic, life is great. Everything works nice, right until you try it in IE. Nothing happens. Turns out that in IE 'this' refers to the Window object (if I remember correctly), which is quite nice, but of no use at all.

The best solution I could find, is that I attach the event to the DIV like this:

objref.attachEvent('onclick', var retek=function() { EventHandler(objref); });

So I use an anonymous function and I pass the object reference (the DIV) into the event handler. Very 'nice' solution, but works like a charm. I use the 'retek' variable to store a reference to the function, because without that, I cannot detach it later with detachEvent.

You can also pass the Event object, it makes things a bit easier later:

objref.attachEvent('onclick', var retek=function() { EventHandler(window.event, objref); });

I do not understand why do I have to rape Javascript when I need something as simple as this. Microsoft please go to hell.