Monday, June 3, 2024
159
rated 0 times [  164] [ 5]  / answers: 1 / hits: 24899  / 14 Years ago, thu, march 17, 2011, 12:00:00

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!


More From » internet-explorer

 Answers
3

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
});

[#93221] Wednesday, March 16, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ibrahimr

Total Points: 468
Total Questions: 99
Total Answers: 93

Location: Serbia
Member since Sun, Jul 11, 2021
3 Years ago
;