Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript "this" losing context in IE

The following works fine in firefox/safari/chrome, in IE, "this" appears to be losing context in the handleEvent() function...the result of the alert is [object Window], which is not what I want; when output from handleEvent(), "this" needs to be a reference to the HandleClick object, not the Window object.

Am I missing something basic which is causing this in IE?

<html>
<head>
<script type="text/javascript">
HandleClick = function(el) {
    this.element = document.getElementById(el);
    if( this.element.addEventListener ) {
        this.element.addEventListener("click", this, false);
    } else {
        if( this.element.attachEvent ) {
            this.element.attachEvent("onclick", this.handleEvent);
        }
    }
}
HandleClick.prototype = {
    handleEvent: function(e) {
        alert(this);
    }
}
</script>
</head>
<body onload="new HandleClick('logo')"></body>
</html>
like image 428
ahallerblu Avatar asked Mar 22 '26 17:03

ahallerblu


1 Answers

.attachEvent() doesn't give you this as the element. You'd need to wrap the handler in a function that invokes it from the context of the element to which it is attached.

    if( this.element.attachEvent ) {
        var that = this;
        this.element.attachEvent("onclick", function() { 
                                              that.handleEvent.call( that.element );
                                           } );
    }
like image 123
user113716 Avatar answered Mar 25 '26 06:03

user113716



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!