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程式設計有所幫助。

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。

JavaScript框架的強大之處在於簡化開發、提升用戶體驗和應用性能。選擇框架時應考慮:1.項目規模和復雜度,2.團隊經驗,3.生態系統和社區支持。

引言我知道你可能會覺得奇怪,JavaScript、C 和瀏覽器之間到底有什麼關係?它們之間看似毫無關聯,但實際上,它們在現代網絡開發中扮演著非常重要的角色。今天我們就來深入探討一下這三者之間的緊密聯繫。通過這篇文章,你將了解到JavaScript如何在瀏覽器中運行,C 在瀏覽器引擎中的作用,以及它們如何共同推動網頁的渲染和交互。 JavaScript與瀏覽器的關係我們都知道,JavaScript是前端開發的核心語言,它直接在瀏覽器中運行,讓網頁變得生動有趣。你是否曾經想過,為什麼JavaScr


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器