search
HomeWeb Front-endJS TutorialAnalysis 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!"

//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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software