


Detailed explanation of JavaScript event proxies and delegates_javascript skills
In JavaScript, Agent and Delegate often appear.
So under what circumstances is it used? What is its principle?
Here we introduce the usage and principle of javascript delegate, as well as the delegate interface in Dojo, jQuery and other frameworks.
JavaScript Event Proxy
Event proxies are a very useful and interesting feature in the JS world. When we need to add events to many elements, we can trigger the handler function by adding the event to their parent node and delegating the event to the parent node.
This is mainly due to the browser's event bubbling mechanism. Let's give a specific example to explain how to use this feature.
This example is mainly taken from David Walsh’s related article (How JavaScript Event Delegation Works).
Suppose there is a parent node of UL, which contains many child nodes of Li:
<ul id="list"> <li id="li-1">Li 1</li> <li id="li-2">Li 2</li> <li id="li-3">Li 3</li> <li id="li-4">Li 4</li> <li id="li-5">Li 5</li> </ul>
When our mouse moves over Li, we need to obtain the relevant information of this Li and pop up a floating window to display detailed information, or when a Li is clicked, the corresponding processing event needs to be triggered.
Our usual way of writing is to add some event listeners like onMouseOver or onClick to each Li.
function addListenersLi(liElement) { liElement.onclick = function clickHandler() { //TODO }; liElement.onmouseover = function mouseOverHandler() { //TODO } } window.onload = function() { var ulElement = document.getElementById("list"); var liElements = ulElement.getElementByTagName("Li"); for (var i = liElements.length - 1; i >= 0; i--) { addListenersLi(liElements[i]); } }
If the Li sub-elements in this UL are frequently added or deleted, we need to call the addListenersLi method every time Li is added to add an event handler for each Li node.
This will make the adding or deleting process complex and the possibility of errors.
The solution to the problem is to use the event proxy mechanism. When the event is thrown to the upper parent node, we determine and obtain the event source Li by checking the target object (target) of the event.
The following code can achieve the desired effect:
/ 获取父节点,并为它添加一个click事件 document.getElementById("list").addEventListener("click",function(e) { // 检查事件源e.targe是否为Li if(e.target && e.target.nodeName.toUpperCase == "LI") { // //TODO console.log("List item ",e.target.id," was clicked!"); } });
Add a click event to the parent node. When the child node is clicked, the click event will bubble up from the child node. After the parent node captures the event, it determines whether it is the node we need to process by judging e.target.nodeName. And get the clicked Li node through e.target. In this way, the corresponding information can be obtained and processed.
Event bubbling and capturing
Browser event bubbling mechanism. Different browser manufacturers have different processing mechanisms for capturing and processing events. Here we introduce the standard events defined by W3C for DOM2.0.
The DOM2.0 model divides the event processing process into three stages:
1. Event capture phase,
2. Event target stage,
3. Event bubbling stage.
As shown below:
Event capture: When an element triggers an event (such as onclick), the top-level object document will emit an event stream, which will flow to the target element node along with the nodes of the DOM tree until it reaches the target element where the event actually occurs. . During this process, the corresponding listening function of the event will not be triggered.
Event target: After reaching the target element, execute the corresponding processing function of the event of the target element. If no listening function is bound, it will not be executed.
Event bubbling: starting from the target element and propagating to the top-level element. If there are nodes bound to corresponding event processing functions on the way, these functions will be triggered at once. If you want to prevent events from bubbling, you can use e.stopPropagation() (Firefox) or e.cancelBubble=true (IE) to prevent event bubbling.
delegate function in jQuery and Dojo
Let's take a look at how to use the event proxy interface provided in Dojo and jQuery.
jQuery:
$("#list").delegate("li", "click", function(){ // "$(this)" is the node that was clicked console.log("you clicked a link!",$(this)); });
jQuery’s delegate method requires three parameters, a selector, a time name, and an event handler.
Dojo is similar to jQuery, the only difference is in the programming style:
require(["dojo/query","dojox/NodeList/delegate"], function(query,delegate){ query("#list").delegate("li","onclick",function(event) { // "this.node" is the node that was clicked console.log("you clicked a link!",this); }); })
Dojo’s delegate module is in dojox.NodeList. It provides the same interface as jQuery and the same parameters.
Through delegation, you can realize several benefits of using event delegation for development:
1. There are fewer management functions. There is no need to add a listener function for each element. For similar child elements under the same parent node, events can be handled by delegating them to the listening function of the parent element.
2. You can easily add and modify elements dynamically, and there is no need to modify event bindings due to changes in elements.
3. There are fewer connections between JavaScript and DOM nodes, which reduces the probability of memory leaks caused by circular references.
Using proxies in JavaScript programming
The above introduction is to use the browser bubbling mechanism to add event proxies to DOM elements when processing DOM events. In fact, in pure JS programming, we can also use this programming model to create proxy objects to operate target objects.
var delegate = function(client, clientMethod) { return function() { return clientMethod.apply(client, arguments); } } var Apple= function() { var _color = "red"; return { getColor: function() { console.log("Color: " + _color); }, setColor: function(color) { _color = color; } }; }; var a = new Apple(); var b = new Apple(); a.getColor(); a.setColor("green"); a.getColor(); //调用代理 var d = delegate(a, a.setColor); d("blue"); //执行代理 a.getColor(); //b.getColor();
In the above example, the modification of a is performed by calling the proxy function d created by the delegate() function.
Although this method uses apply (call can also be used) to realize the transfer of the calling object, it hides certain objects from the programming mode and can protect these objects from being accessed and modified casually.
The concept of delegation is used in many frameworks to specify the running scope of methods.
Typical ones include dojo.hitch(scope, method) and ExtJS’s createDelegate(obj, args).
The above is the entire content of this article. I hope it will be helpful to everyone in learning javascript programming.

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

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

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
