detachEvent not working with named inline functions

Posted by Polshgiant on Stack Overflow See other posts from Stack Overflow or by Polshgiant
Published on 2010-03-31T14:12:19Z Indexed on 2010/03/31 14:33 UTC
Read the original article Hit count: 445

I ran into a problem in IE8 today (Note that I only need to support IE) that I can't seem to explain: detachEvent wouldn't work when using a named anonymous function handler.

document.getElementById('iframeid').attachEvent("onreadystatechange", function onIframeReadyStateChange() {
    if (event.srcElement.readyState != "complete") { return; }

    event.srcElement.detachEvent("onreadystatechange", onIframeReadyStateChange); 

    // code here was running every time my iframe's readyState 
    // changed to "complete" instead of only the first time
});

I eventually figured out that changing onIframeReadyStateChange to use arguments.callee (which I normally avoid) instead solved the issue:

document.getElementById('iframeid').attachEvent("onreadystatechange", function () {
    if (event.srcElement.readyState != "complete") { return; }

    event.srcElement.detachEvent("onreadystatechange", arguments.callee);    

    // code here now runs only once no matter how many times the 
    // iframe's readyState changes to "complete"
});

What gives?! Shouldn't the first snippet work fine?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about javascript-events