Home  >  Article  >  Web Front-end  >  Analysis of event model in js

Analysis of event model in js

不言
不言Original
2018-07-14 14:49:311326browse

This article mainly introduces the event model in JavaScript, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

0. Events and event flow

An event is the moment when the browser interacts with the document, such as clicking a button, filling in a form, etc. It is the bridge of communication between Javascript and HTML. DOM is a tree structure. If events are bound to both parent nodes at the same time, when the child nodes are triggered, the order in which these two events occur will involve the content of the event stream, which describes the order in which the page is accepted. Event flow describes the order in which events are received from the page, but what is more interesting is that the IE and Netscape development teams actually proposed almost completely opposite concepts. IE's event flow is an event bubbling flow, while Netscape Communicator's event flow is an event capture flow.

As a result, event streams are mainly divided into two types: event bubbling and event capture.

IE's event flow is called event bubbling, that is, the event is initially received by the most specific element (the node with the deepest nesting level in the document), and then propagates upwards to less specific nodes (the document) ). Another event stream proposed by the Netscape team is called event capturing. The idea of ​​event capturing is that less specific nodes should receive events earlier, and the most specific nodes should receive events last. The purpose of capture is to capture an event before it reaches its intended destination.

The event flow specified by DOM2-level events includes three stages: event capture stage, target stage, and event bubbling stage. The first thing that happens is event capture, which provides the opportunity to intercept the event. Then the actual target receives the event. The final phase is the bubbling phase, where you can respond to events.

1. DOM0-level event model

The DOM0-level event model is an early event model, also known as the original event model. In this model, events will not propagate , that is, there is no concept of event flow. The event binding listening function is relatively simple. To use Javascript to specify an event handler, you must first obtain a reference to the object to be operated.

Each element (including window and document) has its own event handling attributes. These attributes are usually all lowercase, such as onclick. You can specify an event handler by setting this property to a function:

 btn = document.getElementById("myBtn"= "Clicked!"

//HTML事件处理程序<form method="post">
    <input type="text" name="username" value="">
    <input type="button" value="Username" onclick = "alert(username.value)">
</form>

## 2 . DOM2-level event model

In this model, it is divided into three processes: event capture stage, event bubbling stage in target stage 7;

  • Event capturing phase (capturing phase). The event propagates from the document all the way down to the target element, and checks whether the passing nodes are bound to the event listening function, and executes it if so.

  • Event processing phase (target phase). When the event reaches the target element, the listening function of the target element is triggered.

  • Event bubbling phase. The event bubbles from the target element to the document, and checks whether the passing nodes are bound to the event listening function, and executes it if so.

DOM2 level defines two methods for handling the operations of specifying and removing event handlers, addEventListener() and removeEventListener(). All DOM nodes contain these two methods and take three parameters, the name of the event to be handled, the function as the event handler, and a Boolean value. To add an event handler to the click event, you can use:

var btn = document.getElementById("myBtn");
btn.addEventListener("click", functioin() {
    alert(this.id);
}, false);
btn.addEventListener("click", function() {
    alert("Hello Kid");
}, false);

At this time, the execution order is sequential execution: "myBtn" "Hello kid". In IE, the execution order is exactly the opposite.

The way to remove the event listening function is as follows:

var btn = document.getElementById("myBtn");var handler = function() {
    alert(this.id);
};
"click", handler, btn.removeEventListener("click", handler, );

You can only use function expressions as event handlers here, because removeEventListener () When removing, the parameters passed in are required to be the same as those used when adding the application. Event listening functions added through anonymous functions cannot be removed.

3. Event model in IE

IE uses two methods similar to those in DOM: attachEvent() and detachEvent(). Both methods accept the same two parameters, event handler name and event handler function. Since IE8 and earlier versions only support event bubbling, event handlers added through attachEvent() will be added to the bubbling phase. If you use attachEvent() to add an event handler to the button, it is available:

var btn = document.getElementById("myBtn");var handler = function() {
    alert(this.id);
};
btn.attachEvent("onclick", handler);//添加事件处理程序btn.detachEvent("onclick", handler);//删除事件处理程序

4. Event object

DOM The event object in

  • type represents the triggered event type

  • target represents the target of the event

  • currentTarget represents the element where the event handler is currently processing the event

  • cancelable (Boolean) 表明是否可以取消事件的默认行为

  • bubbles (Boolean)表明事件是否冒泡

  • perventDefault()取消事件的默认行为。如果cancelable为true,则可以使用这个方法

  • stopPropagation()取消事件的进一步捕获或冒泡。如果bubbles为true,则可以使用这个方法。

IE中的事件对象

  • type表示被触发的事件类型

  • srcElement表示事件的目标

  • cancelBubble (Boolean)默认是false,将其设为true就可以取消事件冒泡

  • returnValue (Boolean) 默认是true,将其设置为false就可以取消事件的默认行为

        有了上面的事件对象,就可以写出跨浏览器的事件对象封装成事件包裹了。

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){                 //DOM2
            element.removeEventListener(type, handler, false);
        } else if (element.detachEvent){                  //IE
            element.detachEvent("on" + type, handler);
        } else {
            element["on" + type] = null;                  //DOM0        }
    },

    getEvent: function(event){        
    return event ? event : window.event;
    },

    getTarget: function(event){        
    return event.target || event.srcElement;
    },

    preventDefault: function(event){        
    if (event.preventDefault){
            event.preventDefault();
        } else {
            event.returnValue = false;
        }
    },

    stopPropagation: function(event){        
    if (event.stopPropagation){
            event.stopPropagation();
        } else {
            event.cancelBubble = true;
        }
    }};

 以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

通过node.js来调取baidu-aip-SDK实现身份证识别的功能

如何把js变量值传到php

The above is the detailed content of Analysis of event model in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn