detachEvent not working with named inline functions
- by Polshgiant
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?