首頁 web前端 js教程 JavaScript事件代理與委託詳解_javascript技巧

JavaScript事件代理與委託詳解_javascript技巧

May 16, 2016 pm 03:06 PM
javascript 事件代理 委託

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 will be added or deleted frequently, 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();

登入後複製

在上面的範例中,透過呼叫delegate()函數所建立的代理函數d來操作a的修改。

這種方式儘管是使用了apply(call也可以)來實現了調用對象的轉移,但是從編程模式上實現了對某些對象的隱藏,可以保護這些對像不被隨便訪問和修改。

在許多框架中都引用了委託這個概念用來指定方法的運作作用域。

比較典型的如dojo.hitch(scope,method)和ExtJS的createDelegate(obj,args)。

以上就是本文的全部內容,希望對大家學習javascript程式設計有所幫助。

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1421
52
Laravel 教程
1315
25
PHP教程
1266
29
C# 教程
1239
24
如何使用WebSocket和JavaScript實現線上語音辨識系統 如何使用WebSocket和JavaScript實現線上語音辨識系統 Dec 17, 2023 pm 02:54 PM

如何使用WebSocket和JavaScript實現線上語音辨識系統引言:隨著科技的不斷發展,語音辨識技術已成為了人工智慧領域的重要組成部分。而基於WebSocket和JavaScript實現的線上語音辨識系統,具備了低延遲、即時性和跨平台的特點,成為了廣泛應用的解決方案。本文將介紹如何使用WebSocket和JavaScript來實現線上語音辨識系

WebSocket與JavaScript:實現即時監控系統的關鍵技術 WebSocket與JavaScript:實現即時監控系統的關鍵技術 Dec 17, 2023 pm 05:30 PM

WebSocket與JavaScript:實現即時監控系統的關鍵技術引言:隨著互聯網技術的快速發展,即時監控系統在各個領域中得到了廣泛的應用。而實現即時監控的關鍵技術之一就是WebSocket與JavaScript的結合使用。本文將介紹WebSocket與JavaScript在即時監控系統中的應用,並給出程式碼範例,詳細解釋其實作原理。一、WebSocket技

如何利用JavaScript和WebSocket實現即時線上點餐系統 如何利用JavaScript和WebSocket實現即時線上點餐系統 Dec 17, 2023 pm 12:09 PM

如何利用JavaScript和WebSocket實現即時線上點餐系統介紹:隨著網路的普及和技術的進步,越來越多的餐廳開始提供線上點餐服務。為了實現即時線上點餐系統,我們可以利用JavaScript和WebSocket技術。 WebSocket是一種基於TCP協定的全雙工通訊協議,可實現客戶端與伺服器的即時雙向通訊。在即時線上點餐系統中,當使用者選擇菜餚並下訂單

如何使用WebSocket和JavaScript實現線上預約系統 如何使用WebSocket和JavaScript實現線上預約系統 Dec 17, 2023 am 09:39 AM

如何使用WebSocket和JavaScript實現線上預約系統在當今數位化的時代,越來越多的業務和服務都需要提供線上預約功能。而實現一個高效、即時的線上預約系統是至關重要的。本文將介紹如何使用WebSocket和JavaScript來實作一個線上預約系統,並提供具體的程式碼範例。一、什麼是WebSocketWebSocket是一種在單一TCP連線上進行全雙工

JavaScript與WebSocket:打造高效率的即時天氣預報系統 JavaScript與WebSocket:打造高效率的即時天氣預報系統 Dec 17, 2023 pm 05:13 PM

JavaScript和WebSocket:打造高效的即時天氣預報系統引言:如今,天氣預報的準確性對於日常生活以及決策制定具有重要意義。隨著技術的發展,我們可以透過即時獲取天氣數據來提供更準確可靠的天氣預報。在本文中,我們將學習如何使用JavaScript和WebSocket技術,來建立一個高效的即時天氣預報系統。本文將透過具體的程式碼範例來展示實現的過程。 We

簡易JavaScript教學:取得HTTP狀態碼的方法 簡易JavaScript教學:取得HTTP狀態碼的方法 Jan 05, 2024 pm 06:08 PM

JavaScript教學:如何取得HTTP狀態碼,需要具體程式碼範例前言:在Web開發中,經常會涉及到與伺服器進行資料互動的場景。在與伺服器進行通訊時,我們經常需要取得傳回的HTTP狀態碼來判斷操作是否成功,並根據不同的狀態碼來進行對應的處理。本篇文章將教你如何使用JavaScript來取得HTTP狀態碼,並提供一些實用的程式碼範例。使用XMLHttpRequest

javascript如何使用insertBefore javascript如何使用insertBefore Nov 24, 2023 am 11:56 AM

用法:在JavaScript中,insertBefore()方法用於在DOM樹中插入一個新的節點。這個方法需要兩個參數:要插入的新節點和參考節點(即新節點將要插入的位置的節點)。

JavaScript與WebSocket:打造高效率的即時影像處理系統 JavaScript與WebSocket:打造高效率的即時影像處理系統 Dec 17, 2023 am 08:41 AM

JavaScript是一種廣泛應用於Web開發的程式語言,而WebSocket則是一種用於即時通訊的網路協定。結合二者的強大功能,我們可以打造一個高效率的即時影像處理系統。本文將介紹如何利用JavaScript和WebSocket來實作這個系統,並提供具體的程式碼範例。首先,我們需要明確指出即時影像處理系統的需求和目標。假設我們有一個攝影機設備,可以擷取即時的影像數

See all articles