Javascript 不使用库的 IE 中的自定义事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5342917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:45:23  来源:igfitidea点击:

Custom events in IE without using libraries

javascriptinternet-explorerevents

提问by HumanCatfood

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

我的任务是在不使用任何库(如 jQuery 或原型)的情况下触发文档上的自定义事件。

So I'm ok on Firefox doing this:

所以我在 Firefox 上没问题:

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):

并像这样捕获它(在这里我可以使用 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 )?

我的问题是,我该怎么做才能在 IE 上完成这项工作(换句话说,我把 xxxxxxxxxxx 放在哪里)?

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

我认为 IE 等价物应该是这样的:

 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)

但这不起作用。IE 允许我只使用预定义的事件名称(onclick 等),甚至其中一些不起作用(例如 onmessage)

Any help or ideas are appreciated!

任何帮助或想法表示赞赏!

采纳答案by screenm0nkey

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.

好的,基于 dean edwards 的那篇文章,我写了这个,这似乎可行,但似乎很笨拙。下面的示例基于嵌套在 #one 中的元素 #two,因此我们可以模拟事件冒泡,因为我无法在 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
});

回答by Serg Hospodarets

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

在没有任何框架的情况下在 Javascript 中添加/删除/触发事件/自定义事件:

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

现场演示

回答by JaredMcAteer

Prototype uses the ondataavailable event to fire custom events in IE

Prototype 使用 ondataavailable 事件在 IE 中触发自定义事件