Frontendplace Blog

Sharing Frontend developing ideas

Solved Leak in IE

Posted by info on August 12th, 2008

For javascripters it is well know that IE browsers have problems with memory leaking.. but this problem took me while to find..

On several sites I attach events based on the classname of an element. I have to remove these attached events on unload. So I did. but somehow I always have one element leaking in IE ( mostly an element that i didn’t attach anything on it, so that puzzled me) 

The problem was in the getEvent function I used to convert a fired event to W3C standard. this was my code:

function getEvent(e) {
 if (e == null) {
  e = window.event;
 }
 if (e == null) {
  return null;
 } 
if (!e.target) {
  e.target = e.srcElement;
 }
 // get parent if nodetype is textnode
     if (e.target.nodeType == 3) {
     e.target = e.target.parentNode;
 }
 if (!e.stopPropagation) {
  e.stopPropagation = function() {
   e.cancelBubble = true;
  }
 }
 if (!e.preventDefault) {
  e.preventDefault = function() {
   e.returnValue = false;
  }
 }
 return  e;
}

 

But calling this function caused the leak.
when I changed this function to this underlying code the leak was gone…….hooray!!!


/**
* Returns an event object that is normalized for cross-browser support.
*
* @param {Event} e Event object. Is allowed to be null.
* @returns {Event} A normalized event object.
*/
function getEvent(e) {
    if (e == null) {
  e = window.event;
 }
 if (e == null) {
  return null;
 }
 if (!e.target || !e.stopPropagation || !e.stopPropagation) e = W3CEvent(e);
 
 return  e;
}

/**
* Returns a synthetic event object with partial compatibility with W3C events
*
* @param {Event} e Event object.
* @returns {event} The partial W3C event object.
*/
function W3CEvent(e) { 
    if (!e) e = window.event;
    var event = {
        _event: e,              // In case we really want the IE event object
        type: e.type,           // Event type
        target: e.target?e.target:e.srcElement,   // Where the event happened
        relatedTarget: e.fromElement?e.fromElement:e.toElement,
        keyCode: e.keyCode,
       
        // Mouse coordinates
        clientX: e.clientX,
        clientY: e.clientY,
        screenX: e.screenX,
        screenY: e.screenY,
       
        // Key state
        altKey: e.altKey,
        ctrlKey: e.ctrlKey,
        shiftKey: e.shiftKey,
        charCode: e.keyCode,

        // Event management functions
        stopPropagation: function(){this._event.cancelBubble = true;},
        preventDefault: function(){this._event.returnValue = false;}
    }
    return event;
};

why???? if someone can tell me why please respond..