Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement event proxy and delegation in JavaScript

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "how to realize event proxy and delegation in JavaScript". The editor shows you the operation process through an actual case, and the operation method is simple, fast and practical. I hope this article "how to realize event proxy and delegation in JavaScript" can help you solve the problem.

JavaScript event Agent

Let's start with an introduction to JavaScript's event broker. Event broker is a very useful and interesting feature in the JS world. When we need to add events to many elements, we can trigger the handler by adding the event to their parent node and delegating the event to the parent node. This is mainly due to the event bubbling mechanism of the browser, which will be described in more detail later. Let's give a specific example to explain how to use this feature. This example is mainly taken from the related article (How JavaScript Event Delegation Works) of David Walsh.

Suppose you have a parent node of UL that contains many children of Li:

Item 1 Item 2 Item 3 Item 4 Item 5 Item 6

When we move the mouse over the Li, we need to get the relevant information about the Li and float out the suspension window to display the details, or when a Li is clicked, we need to trigger the corresponding processing event. Our usual way of writing is to add event listeners such as onMouseOver or onClick for each Li.

Function addListeners4Li (liNode) {liNode.onclick = function clickHandler () {...}; liNode.onmouseover = function mouseOverHandler () {...}} _ window.onload = function () {var ulNode = document.getElementById ("parent-list"); var liNodes = ulNode.getElementByTagName ("Li"); for (var iNodes 0, l = liNodes.length; I < l; iNodes +) {addListeners4Li (liNodes [I]);}}

If the Li child elements in this UL are frequently added or deleted, we need to call this addListeners4Li method every time we add a Li to add event handlers for each Li node. This adds complexity and the possibility of error.

An easier way is to use the event broker mechanism. When the event is thrown to the parent node of the higher level, we determine and obtain the event source Li by checking the event target object (target). The following code can achieve the desired effect:

/ / get the parent node and add a click event document.getElementById ("parent-list") .addEventListener ("click", function (e) {/ / check whether the event source e.targe is Li if (e.target & & e.target.nodeName.toUpperCase = = "LI") {/ / the real processing is here console.log ("List item", e.target.id.replace ("post-"), "was clicked!") })

Add a click event for the parent node, and when the child node is clicked, the click event bubbles up from the child node. After the parent node captures the event, it determines whether it is the node we need to deal with by judging the e.target.nodeName. And get the clicked Li node through e.target. Thus, the corresponding information can be obtained and processed.

Event bubbling and capture

The event bubbling mechanism of browsers has been mentioned in the previous introduction. Here is a more detailed description of the browser's handling of the DOM event. For the capture and handling of events, different browser vendors have different handling mechanisms. Here we mainly introduce the standard events defined by W3C for DOM2.0.

DOM2.0 model divides the event processing process into three stages: first, the event capture stage, second, the event target stage, and third, the event blistering stage. As shown in the figure:

Event capture: when an element triggers an event (such as onclick), the top-level object document emits an event stream as the node of the DOM tree flows to the target element node until it reaches the target element where the event actually occurs. In this process, the listener function corresponding to the event will not be triggered.

Event target: when the target element is reached, the handler function corresponding to the event of the target element is executed. If the listener function is not bound, it is not executed.

Event blistering: propagates from the target element to the top-level element. On the way, if a node binds the corresponding event handler, these functions will be triggered once. If you want to stop the event from bubbling, you can use e.stopPropagation () (Firefox) or e.cancelBubble=true (IE) to organize the bubble propagation of the event.

Delegate function in jQuery and Dojo

Let's take a look at how to use the event broker interface provided in Dojo and jQuery.

Delegate ("a", "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, except for the difference in programming style:

Require (["dojo/query", "dojox/NodeList/delegate"], function (query,delegate) {query ("# link-list") .delegate ("a", "onclick", function (event) {/ / "this.node" is the node that was clicked console.log ("you clicked a link!", this);})

The delegate module of Dojo is in dojox.NodeList and provides the same interface and parameters as jQuery.

Advantages from the above introduction, you should be able to appreciate several advantages of using event delegates for web applications:

1. There are fewer functions to manage. You don't need to add a listening function for every element. For similar child elements under the same parent node, events can be handled through the listener function delegated to the parent element.

two。 You can easily add and modify elements dynamically, without the need to modify event bindings because of element changes.

There are fewer associations between 3.JavaScript and DOM nodes, which reduces the probability of memory leaks due to circular references.

At this point, I suddenly remembered the previous confusion about Dojo DataGrid: how to deal with the relationship between so many rows and cells events. Now that you think about it, it's easy to use a delegate. All events are delegated to the outermost node of the grid, and when the event occurs, additional attributes of the event are obtained and added through some methods, such as rowIndex, cellIndex, and then assigned to handler functions such as onRowClick,onCellClick.

Using agents in JavaScript programming

The above describes the use of browser bubbling mechanism to add event proxies for DOM elements when handling DOM events. In fact, in pure JS programming, we can also use this programming mode to create a proxy object to manipulate the target object. Here is an example from Szeto Zhengmei's related article:

Var delegate = function (client, clientMethod) {return function () {return clientMethod.apply (client, arguments);}} var ClassA = function () {var _ color = "red"; return {getColor: function () {console.log ("Color:" + _ color) }, setColor: function (color) {_ color = color;}};}; var a = new ClassA (); a.getColor (); a.setColor ("green"); a.getColor (); console.log ("execute Agent!") ; var d = delegate (a, a.setColor); d ("blue"); console.log ("execution complete!") ; a.getColor ()

In the above example, the modification to an is operated by calling the proxy function d created by the delegate () function. Although this method uses apply (call can also) to achieve the transfer of calling objects, but from the programming mode to achieve the hiding of some objects, can protect these objects from being casually accessed and modified.

The concept of delegate is referenced in many frameworks to specify the running scope of the method. Typical ones such as dojo.hitch (scope,method) and ExtJS's createDelegate (obj,args).

This is the end of the introduction to "how JavaScript implements event agents and delegates". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report