Home Web Front-end JS Tutorial Analysis of event model in js

Analysis of event model in js

Jul 14, 2018 pm 02:49 PM

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!"
Copy after login

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

## 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);
Copy after login

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);
};
Copy after login
"click", handler, btn.removeEventListener("click", handler, );
Copy after login

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);//删除事件处理程序
Copy after login

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;
        }
    }};
Copy after login

 以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles