IEvent: Better Event Dispatching

In recent years working with events has become very cross browser. We really don’t need anything but straight modern standards vanilla JS anymore for most event dealings as long as we only need IE9+ (which for many projects is now the case). We have great cross-browser methods such as addEventListener and removeEventListener for dealing with listeners, and you can dispatch events with a simple dispatchEvent and create them with the new operator.

However, there’s still one issue. Internet Explorer takes issue with making events via the new operator. Internet Explorer doesn’t recognize the syntax new Event('eventType') and requires you to use deprecated functions that are a bad idea for keeping your code running well in the future.


The Solution

I have a way of handling this that I like to use, and I’d like to share it. I make a JS class named IEvent (get it...like Event, and IE mashed together?). With this class you can use standard compliant coding, but just with an “I” in front of the “Event", which will work equally well in compliant modern browsers (Chrome, Safari, FireFox, etc.) as well as work for IE. In fact, it’s the actual Event that gets returned, not an instance of IEvent. The IEvent class simply works some magic to make that happen. Here would be a usage example:

var evt = new IEvent('myEventName');
window.dispatchEvent(evt);

Notice that the only difference in syntax between this and normal standards Event creation is the “I” in front of Event, so really easy to use.


The Code

Here’s the code itself:

// Free under MIT License | for info: http://mbmedia.cc/stuff/ievent
function IEvent(type, initObj)
{
    try {
        return new Event(type, initObj);
    } catch(err) {
        if (initObj === undefined) initObj = {};
        var evt = document.createEvent('Event');
        evt.initEvent(type, !!initObj.bubbles, !!initObj.cancelable);
        return evt;
    }
}

Notice that it returns the actual Event object created, rather than leaving the new operator to implicitly return the instance of the constructor itself. Since the class even returns the actual Event object, so there’s no difference between this and new Event() except for some internal magic making it work for IE.

Basically, it tries to do it the standard way, and if there’s an error then it falls back to the IE way. The advantage of this is that standards compliant browsers have barely any overhead from a try statement that doesn’t actually trip an error, and only IE users have the (silent/handled) error and have to move to the catch statement.

The API is the exact same as normal creation of a new Event object. So there’s nothing to learn. Just start using!