Small compatibility - - addEventListener() and attachEvent() cross-browser compatibility processing

Keywords: IE Javascript

Similarities and differences between addEventListener() and attachEvent()

Similarities:
They are all methods of dom objects, which can bind multiple event handlers to an event.
(2) Compared with the common DOM event processing element.event = fun(); when using attachEvent and addEventListener, multiple event handling functions can be called.

Difference:
attachEvent is a method of IE. It does not follow the W3C standard, while other mainstream browsers such as FF and other browsers that follow the W3C standard use addEventListener, so it needs to be dealt with separately in actual development - involving compatibility.
(2) The order of execution after multiple binding is different. attachEvent is executed first after binding, and addEventListener is executed first after binding.
(3) When binding time, attachEvent must take on, such as on click, on mouseover, etc., while addEventListener cannot take on, such as click, mouseover;
(4) attachEvent only needs to pass two parameters, while addEventListener needs to pass three parameters, which involves the concept of "event flow". There are three stages in listening: capture stage, target stage and bubbling stage. The order is: capture stage (check whether the listener function is called from root node to child node)target stage (target itself)bubble stage (target itself to root node). The parameters here determine whether the listener runs in the capture phase, the target phase, or the bubbling phase. If useCapture is set to true, the listener handles events only in the capture phase, not in the target or bubbling phase. If useCapture is false, the listener handles events only at the target or bubbling stage. To listen for events in all three stages, call addEventListener twice, set useCapture to true once, and set useCapture to false the second time.

The understanding of (4) can be transferred to: Click here. (Explain these two parameters and fill in the conceptual understanding of event bubbling and event capture)

Example:

// Ordinary Event Handler - Execute only the last event binding function (Execute only the last bound event callback >> 3)
        btn.onclick = function(){alert(1);}
        btn.onclick = function(){alert(2);}
        btn.onclick = function(){alert(3);}
// Attach Event Event Event Event Handler Call - Bind First Execute (IE8 - > 321)
        btn1.attachEvent("onclick",function(){ alert(1); })
        btn1.attachEvent("onclick",function(){ alert(2); })
        btn1.attachEvent("onclick",function(){ alert(3); })
 // AdEventListener Event Handler - First Bind First Execute (IE9+/Mainstream Browser >> 123)
        btn2.addEventListener("click",function(){ alert(1); },false)
        btn2.addEventListener("click",function(){ alert(2); },false)
        btn2.addEventListener("click",function(){ alert(3); },false)

Encapsulation - Ways for Different Browsers to Listen for Events and Clear Events

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <button id="btn">Point me</button>
</body>
<script type="text/javascript">
    var EventUtil = {
        addHandler : function(element,type,handler){
            if(element.addEventListener){
                element.addEventListener(type,handler,false);
            }else if(element.attachEvent){
                element.attachEvent('on' + type,handler);
            }else{
                element['on' + type] = handler;
            }
        },
        removeHandler : function(element,type,handler){
            if(element.removeEventListener){
                element.removeEventListener(type,handler,false);
            }else if(element.detachEvent){
                element.detachEvent('on' + type,handler);
            }else{
                element['on' + type] = null;
            }
        }
    }
    var btn = document.getElementById('btn');
    var handler = function(){
        console.log('Hello World!');
        /* Remove events */
        // EventUtil.removeHandler(btn,'click',handler);
    }
    /* Adding Events */
    EventUtil.addHandler(btn,'click',handler);
</script>
</html>

Using hash value-table encapsulation

function addEvent(element, type, handler) {
            //Assign a unique ID to each event handler
            if (!handler.$$guid) handler.$$guid = addEvent.guid++;
            //Create a hash table for the event type of the element
            if (!element.events) element.events = {};
            //Create a hash table for each "element/event" pair of event handlers
            var handlers = element.events[type];
            if (!handlers) {
                handlers = element.events[type] = {};
                //Store existing event handlers (if any)
                if (element["on" + type]) {
                    handlers[0] = element["on" + type];
                }
            }
            //Store event handlers in hash tables
            handlers[handler.$$guid] = handler;
            //Assign a global event handler to do all the work
            element["on" + type] = handleEvent;
        };
        //Counter used to create a unique ID
        addEvent.guid = 1;
        function removeEvent(element, type, handler) {
            //Delete event handlers from hash tables
            if (element.events && element.events[type]) {
                delete element.events[type][handler.$$guid];
            }
        };
        function handleEvent(event) {
            var returnValue = true;
            //Capture event objects (IE uses global event objects)
            event = event || fixEvent(window.event);
            //Gets a reference to the hash table of the event handler function
            var handlers = this.events[event.type];
            //Execute each processing function
            for (var i in handlers) {
                this.$$handleEvent = handlers[i];
                if (this.$$handleEvent(event) === false) {
                    returnValue = false;
                }
            }
            return returnValue;
        };
        //Adding "missing" functions to IE event objects -- Bubble compatible IE processing
        function fixEvent(event) {
            //Adding standard W3C method
            event.preventDefault = fixEvent.preventDefault;
            event.stopPropagation = fixEvent.stopPropagation;
            return event;
        };
        fixEvent.preventDefault = function () {
            this.returnValue = false;
        };
        fixEvent.stopPropagation = function () {
            this.cancelBubble = true;
        };

Posted by spasme on Thu, 25 Jul 2019 01:58:05 -0700