Posted By


oronm on 09/05/06

Tagged


Statistics


Viewed 304 times
Favorited by 3 user(s)

Rock Solid addEvent


/ Published in: JavaScript
Save to your folder(s)

In the aftermath of the addEvent() recoding contest, a winner was announced. It was also further discussed in the particleTree November issue with another method provided (I won’t discuss it since it’s copyrighted content and it’s for paying customers only ;) ). However even with all the fuss going on, I’ve taken an innovative approach with some existing methods and combined them into a very powerful function. It also accomplishes these three core issues.

* Degrades on older browsers such as NS4 and IE5 mac
* The this keyword remains in-tact
* Avoids memory leaks in Microsoft Internet Explorer

Since none of this is entirely revolutionary or actually originally written by me, I’m not going to take any further credit other than piecing together what was already out there.
Introducing, my addEvent()

Here for your copy and pasting pleasure, it consists of three parts. 1) The addEvent() function itself which programatically adds to the 2) EventCache (originally written by Mark Wubben), and 3) an unload event is added to the window to run the EventCache ‘flush’ method.


Copy this code and paste it in your HTML
  1. function addEvent( obj, type, fn ) {
  2. if (obj.addEventListener) {
  3. obj.addEventListener( type, fn, false );
  4. EventCache.add(obj, type, fn);
  5. }
  6. else if (obj.attachEvent) {
  7. obj["e"+type+fn] = fn;
  8. obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
  9. obj.attachEvent( "on"+type, obj[type+fn] );
  10. EventCache.add(obj, type, fn);
  11. }
  12. else {
  13. obj["on"+type] = obj["e"+type+fn];
  14. }
  15. }
  16.  
  17. var EventCache = function(){
  18. var listEvents = [];
  19. return {
  20. listEvents : listEvents,
  21. add : function(node, sEventName, fHandler){
  22. listEvents.push(arguments);
  23. },
  24. flush : function(){
  25. var i, item;
  26. for(i = listEvents.length - 1; i >= 0; i = i - 1){
  27. item = listEvents[i];
  28. if(item[0].removeEventListener){
  29. item[0].removeEventListener(item[1], item[2], item[3]);
  30. };
  31. if(item[1].substring(0, 2) != "on"){
  32. item[1] = "on" + item[1];
  33. };
  34. if(item[0].detachEvent){
  35. item[0].detachEvent(item[1], item[2]);
  36. };
  37. item[0][item[1]] = null;
  38. };
  39. }
  40. };
  41. }();
  42. addEvent(window,'unload',EventCache.flush);

URL: http://www.dustindiaz.com/rock-solid-addevent/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.