Garry Polley
Garry Polley

Reputation: 4443

How to wrap attachEvent in IE8

Right now we are working on a way to catch errors that occur in JavaScript. We have everything working in browsers including and after IE9.

In modern browsers we can wrap window.EventTarget.prototype.addEventListener with a function that does a try/catch in order to capture errors. For example we can do this:

var addEventListener = window.EventTarget.prototype.addEventListener;

window.EventTarget.prototype.addEventListener = function (event, callback, bubble) {
return addEventListener.call(this, event, WATCH_FUNCTION(callback), bubble)
};

The WATCH_FUNCTION above has our try/catch in it. Right now we cannot figure out a way to wrap the attachEvent that exists on an element in IE8. For example:

var myObject = document.getElementById('my-id');

myObject.attachEvent('onclick', function () {reference-to-undefined-var});

Our hope is to wrap the error that is going to be raised by the attached event. Right now we cannot figure out how to always wrap attachEvent. We will be a third party library so we cannot force people to use a different form of attaching events.

As a note for anyone who looks at this question I have tried to override the following and none seem to work:

Upvotes: 1

Views: 640

Answers (1)

Garry Polley
Garry Polley

Reputation: 4443

I finally figured out what I had been doing wrong and the following appears to be working in IE8. For all other browsers you can simply override the window.EventTarget versions. Basically I was missing the use of the call, without that it does not know the context of what's making the call to attachEvent.

var attachEvent = window.Element.prototype.attachEvent,
      detachEvent = window.Element.prototype.detachEvent;

  window.Element.prototype.attachEvent = function (event, callback) {
    return attachEvent.call(this, event, watch(callback));
  };

  window.Element.prototype.detachEvent = function (event, callback) {
    return detachEvent.call(this, event, watch(callback));
  };

Upvotes: 1

Related Questions