« CSS Ratings Selector | Main | Two AJAX classes nominee for the Innovation Award September 2005 »

addEvent() considered harmful

QuirksBlog have an interesting article about addEvent() and how it is considered harmful.

Back in 2001 Scott Andrew LePera published the cross browser event handler script addEvent(), which was subsequently copied, revised, and used in many, many websites. I never used it, because I felt — and feel — it is wrong to assume that the W3C addEventListener and the Microsoft attachEvent methods are the same. They aren't, and the slight but important difference can trip up the unwary web developer.

There is many possible solutions like the Event.observe in Prototype, There is AddEvent Manager which not only does it allow multiple events to be attached to one object in both IE/Mac and IE/Win as well as DOM-Events-compliant browsers, but the "this" keyword operates correctly in all the aforementioned. Plus, it tracks and removes event ONUNLOAD to stop IE memory leaks.

Bookmark this article at these sites
Comments
1

I was completely confused by the error handling for JS. I've managed to keep things simple for the time being (i need more time!!!) and the addEvent function is an example of this.

Instead of playing with the addEventListener/attachEvent functionality, I decided to do something a little simpler - re-write the specific event handler code.

E.g. (excuse the poor pseudo code)
function addEvent( oElement, strEventHandler, strActions ){
is oElement.strEventHandler defined yet?
Yes: append strActions to the end of the ciurrent function declaration
No: set the curent function decleration to strActions
}

so
addEvent( form1.btn_go, "onclick", "alert('the go button was clicked');")
addEvent( form1.btn_go, "onclick", "window.location.href='www.zging.com';");

is the equivelant of:

form1.btn_go.onclick= function (){
alert('the go button was clicked');
window.location.href='www.zging.com';
}

This is dead simple and it works... but I haven't investigated any side effects, or reasons for it being a bad method.

Any opinions?

2

Personaly I can't see what is wrong with addEvent, I was using without problem too, but I need to make more tests to see.

I think the problem is mainly caused by IE implementation of addEvent() which isnt compatible with the W3C addEventListener.

Post a comment





(Email will remain hidden)





Please enter the security code you see here




Related entries
Email to a friend
Email this article to:


Your email address:


Message (optional):