This time I will bring you what are the event handling rules in web development, what are the notes of event handling in web development, the following is a practical case, let’s take a look .
Event processing
We know that when an event is triggered, the event object (event object) will be passed into the event handler as a callback parameter. For example:
// 不好的写法function handleClick(event) { var pop = document .getElementById('popup'); popup.style.left = event.clientX + 'px'; popup.style.top = event.clientY + 'px'; popup.className = 'reveal'; }// 你应该明白addListener函数的意思addListener(element, 'click', handleClick);
This code only uses two attributes of the event object: clientX and clientY. Use these two attributes to position the element before displaying it on the page. Although this code looks very simple and has no problems, it is actually a bad way to write it because this approach has its limitations.
Rule 1: Isolate application logic
The first problem with the above example code is that the event handler contains application logic. Application logic is functional code related to the application, not to user behavior. The application logic in the above example code is to display a pop-up box at a specific location. Although this interaction should occur when the user clicks on a specific element, this is not always the case.
It is a best practice to separate application logic from all event handlers, because you never know when the same logic will be triggered elsewhere. For example, sometimes you need to determine whether to display a pop-up box when the user moves the mouse over an element, or make the same logical judgment when a certain key on the keyboard is pressed. In this way, multiple event handlers execute the same logic, but your code is accidentally copied multiple times.
Another disadvantage of placing application logic in event handlers is related to testing. When testing, you need to trigger the function code directly instead of simulating a click on the element. If your application logic is placed in an event handler, the only way to test it is to cause the event to fire. Although some testing frameworks can simulate triggering events, in practice this is not the best approach to testing. The best way to call functional code is with a single function call.
You always need to separate application logic and event handling code. If you want to refactor the previous example code, the first step is to put the code that handles the pop-up box logic into a separate function. This function is likely to be mounted on a global object defined for the application. The event handler should always be in the same global object, so there are two methods.
// 好的写法 - 拆分应用逻辑var MyApplication = { handleClick: function (event) { this.showPopup(event); }, showPopup: function (event) { var pop = document.getElementById('popup'); popup.style.left = event.clientX + 'px'; popup.style.top = event.clientY + 'px'; popup.className = 'reveal'; } }; addListener(element, 'click', function (event) { MyApplication.handleClick(event); });
All application logic previously contained in event handlers is now moved to the MyApplication.showPopup() method. Now the MyApplication.handleClick() method only does one thing, which is to call MyApplication.showPopup(). If the application logic is stripped out, calls to the same functional code can occur at multiple points, and there is no need to rely on the triggering of a specific event, which is obviously more convenient. But this is only the first step in breaking down the event handler code.
Rule 2: Do not distribute event objects
After stripping out the application logic, there is still a problem in the above example code, that is, event objects are distributed uncontrollably. It passes MyApplication.handleClick() from the anonymous event handler, which then passes it to MyApplication.showPopup(). As mentioned above, the event object contains a lot of additional information related to the event, and this code only uses two of them. Application logic should not rely on event objects to complete functions correctly for the following reasons:
The method interface does not indicate which data is necessary. A good API must be transparent about expectations and dependencies. Passing an event object as a parameter does not tell you which properties of the event are useful and what they are used for?
Therefore, if you want to test this method, you must recreate an event object and pass it as a parameter enter. Therefore, you need to know exactly what information this method uses so that you can write the test code correctly.
These problems (referring to unclear interface format and self-constructed event objects for testing) are not advisable in large-scale Web applications. Lack of clarity in code can lead to bugs.
The best way is to let the event handler use the event object to handle the event, and then get all the required data and pass it to the application logic. For example, the MyApplication.showPopup() method only requires two pieces of data, the x coordinate and the y coordinate. In this way, we will rewrite the method so that it receives these two parameters.
// 好的写法var MyApplication = { handleClick: function (event) { this.showPopup(event.clientX, event.clientY); }, showPopup: function (x, y) { var pop = document.getElementById('popup'); popup.style.left = x + 'px'; popup.style.top = y + 'px'; popup.className = 'reveal'; } }; addListener(element, 'click', function (event) { MyApplication.handleClick(event); });
在这段新重写的代码中,MyApplication.handleClick()将x坐标和y坐标传入了MyApplication.showPopup(),代替了之前传入的事件对象。可以很清晰地看到MyApplication.showPopup()所期望传入的参数,并且在测试或代码的任意位置都可以很轻易地直接调用这段逻辑,比如:
// 这样调用非常棒MyApplication.showPopup(10, 10);
当处理事件时,最好让事件处理程序成为接触到event对象的唯一的函数。事件处理程序应当在进入应用逻辑之前针对event对象执行任何必要的操作,包括阻止默认事件或阻止事件冒泡,都应当直接包含在事件处理程序中。比如:
// 好的写法var MyApplication = { handleClick: function (event) { // 假设事件支持DOM Level2 event.preventDefault(); event.stopPropagation(); // 传入应用逻辑 this.showPopup(event.clientX, event.clientY); }, showPopup: function (x, y) { var pop = document.getElementById('popup'); popup.style.left = x + 'px'; popup.style.top = y + 'px'; popup.className = 'reveal'; } }; addListener(element, 'click', function (event) { MyApplication.handleClick(event); });
在这段代码中,MyApplication.handleClick()是事件处理程序,因此它在将数据传入应用逻辑之前调用了event.preventDefault()和event.stopPropagation(),这清除地展示了事件处理程序和应用逻辑之间的分工。因为应用逻辑不需要对event产生依赖,进而在很多地方都可以轻松地使用相同的业务逻辑,包括写测试代码。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of What are the event handling rules in web development?. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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.

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.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.