Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom events in IE without using libraries

I am tasked to fire custom events on the document without using any libraries like jQuery or prototype.

So I'm ok on Firefox doing this:

function fireCustomEvent(eventData)
{
    if (document.createEvent)   // Firefox
    {
        var event = document.createEvent('HTMLEvents');    // create event
        event.initEvent('myCustomEvent', true, true );     // name event
        event.data = eventData;                            // put my stuff on it
        document.dispatchEvent(event);                     // fire event
    }
    else if (document.createEventObject)    // IE
    {
        xxxxxxxxxxx
    }
}

and now I can fire it like this:

fireCustomEvent({
    category: 'test',
    value: 123
});

and catch it like this (here I can use jQuery):

$(document).bind('myCustomEvent', function (event) {
    doStuff(event);
});

My question is, what can I do to make this work on IE (in other words, where I put the xxxxxxxxxxx )?

I think that the IE-equivalent should look something like this:

 var event = document.createEventObject();
 event.data = eventData;
 document.fireEvent('myCustomEvent', event);

But that doesn't work. IE lets me use only predefined event-names (onclick, etc) and even some of those don't work (onmessage for example)

Any help or ideas are appreciated!

like image 731
HumanCatfood Avatar asked Mar 17 '11 17:03

HumanCatfood


3 Answers

Add/Remove/Fire Events/Custom Events in Javascript without any frameworks:

var htmlEvents = {// list of real events
    //<body> and <frameset> Events
    onload:1,
    onunload:1,
    //Form Events
    onblur:1,
    onchange:1,
    onfocus:1,
    onreset:1,
    onselect:1,
    onsubmit:1,
    //Image Events
    onabort:1,
    //Keyboard Events
    onkeydown:1,
    onkeypress:1,
    onkeyup:1,
    //Mouse Events
    onclick:1,
    ondblclick:1,
    onmousedown:1,
    onmousemove:1,
    onmouseout:1,
    onmouseover:1,
    onmouseup:1
}
function triggerEvent(el,eventName){
    var event;
    if (typeof window.CustomEvent === 'function') {
        event = new CustomEvent(eventName);
    } else if (document.createEvent) {
        event = document.createEvent('HTMLEvents');
        event.initEvent(eventName,true,true);
    }else if(document.createEventObject){// IE < 9
        event = document.createEventObject();
        event.eventType = eventName;
    }
    event.eventName = eventName;
    if(el.dispatchEvent){
        el.dispatchEvent(event);
    }else if(el.fireEvent && htmlEvents['on'+eventName]){// IE < 9
        el.fireEvent('on'+event.eventType,event);// can trigger only a real event (e.g. 'click')
    }else if(el[eventName]){
        el[eventName]();
    }else if(el['on'+eventName]){
        el['on'+eventName]();
    }
}
function addEvent(el,type,handler){
    if(el.addEventListener){
        el.addEventListener(type,handler,false);
    }else if(el.attachEvent && htmlEvents['on'+type]){// IE < 9
        el.attachEvent('on'+type,handler);
    }else{
        el['on'+type]=handler;
    }
}
function removeEvent(el,type,handler){
    if(el.removeEventListener){
        el.removeEventListener(type,handler,false);
    }else if(el.detachEvent && htmlEvents['on'+type]){// IE < 9
        el.detachEvent('on'+type,handler);
    }else{
        el['on'+type]=null;
    }
}

var _body = document.body;
var customEventFunction = function(){
    console.log('triggered custom event');
}
// Subscribe
addEvent(_body,'customEvent',customEventFunction);
// Trigger
triggerEvent(_body,'customEvent');

Live demo

like image 145
Serg Hospodarets Avatar answered Nov 03 '22 18:11

Serg Hospodarets


OK Based on that article by dean edwards I wrote this which seems to work but it seems a but hacky. The example below is based on element #two nested inside #one so we can simulate event bubbling as I couldn't see or find a way to bubble custom events in IE.

function bindCustomEvent (el, eventName, eventHandler) {
    if (el.attachEvent) {
        if (!el[eventName]) {
            el[eventName] = 0;
        }
        el.attachEvent("onpropertychange", function (event) {
            if (event.propertyName == eventName) {
                eventHandler(eventHandler);
            }
        });
    }
}

bindCustomEvent(document.documentElement, "fakeEvents", function (evt) {
    alert('document');
});
bindCustomEvent(document.getElementById('one'), "fakeEvents", function (evt) {
    alert('one');
});
bindCustomEvent(document.getElementById('two'), "fakeEvents", function (evt) {
    alert('two');
});

dispatchFakeEvent = function (el, eventName, bubble) {
    bubble = !bubble ? false : true;
    if (el.nodeType === 1 && el[eventName] >= 0) {
        el[eventName]++;
    }
    if (bubble && el !== document) {
        dispatchFakeEvent(el.parentNode, eventName, bubble);
    }
};

document.getElementById('click').attachEvent('onclick', function () {
    dispatchFakeEvent(document.getElementById('two'), 'fakeEvents', true);//false = bubble
});
like image 11
screenm0nkey Avatar answered Nov 03 '22 18:11

screenm0nkey


Prototype uses the ondataavailable event to fire custom events in IE

like image 3
JaredMcAteer Avatar answered Nov 03 '22 17:11

JaredMcAteer