Custom events in IE without using libraries

前端 未结 3 1094
渐次进展
渐次进展 2020-12-12 18:40

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 fi         


        
3条回答
  •  囚心锁ツ
    2020-12-12 19:15

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

提交回复
热议问题