Cute solutions and something else...

Order of Events 8

Published Tuesday, February 21, 2006 by Роман Рахман.

I use prototype.js as many other developers in the world do.
I guess one of the most useful objects in this framework is Event. It’s a really simple way for observing events without any thoughts about difference between Event Model in Internet Explorer and "Truth Nice Browsers" (like Firefox).

You can just write:
Event.observe(window, "load", myLoadHandler);

Dead easy!

But there’s a thing which drives me mad sometimes. It’s the order of event firing. And it’s not a problem of Prototype framework, but problem of Internet Explorer Event Model.

Just a small example (don't forget to include prototype.js):
var count = 2;   
for(var i= 1 ; i<=count; i++) {   
    var handler = new Function('alert('  + i +  ')');   
    Event.observe( window ,  'load' , handler);  
}   

What order of alerts do you see in Firefox? Bingo! 1, 2
In Internet Explorer? Huh, 2, 1

Set count = 3 and repeat.
Firefox? Surely 1, 2, 3
IE? 3, 2, 1? Sorry, actually not! 2, 3, 1. Why? Don’t ask me, please.

Interested? Let’s continue with count = 4
Firefox: 1, 2, 3, 4. If we had got another result I would have eaten my VisiBone
Javascript card

And extra-weird in IE: 2, 4, 3, 1

What’s the method of events ordering that IE uses? Neither FIFO (like Firefox), nor LIFO.
This software makes me more and more unhappy.

BTW, I checked this code in IE 6.0 (Window 2000) and IE 7 b2 (Windows XP).
As you can suspect, the result was the same.

Why did I start from prototype and how is it related to the ugly IE Event Model?

I think it’d be very nice if Sam Stephenson included algorithm which will correct this IE bug to prototype Event object I mean Event.observe() shouldn’t add event handler directly by calling .addEventListener() or .attachEvent() but store handlers in internal hash and call them in right order.

About me

  • I'm Роман Рахман
  • From Донецк, Ukraine
  • My profile

Links