JavaScript event proxy and delegation _ javascript tips-js tutorial

Source: Internet
Author: User
Tags getcolor
This article mainly introduces JavaScript event proxy and delegation in detail. If you are interested, you can refer to javasript, Proxy and DelegationIt often appears.

Under what circumstances does it use? What is its principle?

Here we will introduce the usage and principles of javascript delegate, and the delegate interfaces in frameworks such as Dojo and jQuery.

JavaScript event proxy
Event proxy is a very useful and interesting feature in the JS world. When we need to add events to many elements, we can add events to their parent nodes and delegate the events to the parent node to trigger the processing function.

This is mainly because of the event bubbling mechanism of the browser. The following is an example to explain how to use this feature.

This example is based on How JavaScript Event Delegation Works ).

Assume that there is a UL parent node, which contains many Li subnodes:

 
 
  • Li 1
  • Li 2
  • Li 3
  • Li 4
  • Li 5

When we move the mouse over Li, we need to obtain information about this Li and move it out of the floating window to display details, or, when a Li is clicked, the corresponding processing event needs to be triggered.

We usually add event listening like onMouseOver or onClick for 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 we add Li to add event processing functions for each Li node.

This will cause the complexity of the add or delete process and the possibility of errors.

The solution is to use the event proxy mechanism. When an event is thrown to a parent node on the upper layer, we can check the target object of the event to determine and obtain the event source Li.

The following code can achieve the desired effect:

/Obtain the parent node and add a click event document for it. getElementById ("list "). addEventListener ("click", function (e) {// check whether the event source e.tar ge is Li if(e.tar get & e.tar get. nodeName. toUpperCase = "LI") {// TODO console. log ("List item" ,e.tar get. id, "was clicked! ");}});

Add a click event for the parent node. When the child node is clicked, the click event starts to bubble up from the child node. After the event is caught by the parent node, you can use e.tar get. nodeName to determine whether it is the node we need to process. And get the clicked Li node through e.tar get. In this way, the corresponding information can be obtained and processed.

Event bubbling and capture
Browser event bubbling mechanisms: different browser vendors have different processing mechanisms for event capture and processing. Here we will introduce W3C standard events defined for DOM2.0.

The DOM2.0 model divides the event processing process into three phases:

I. Event capture stage,

Ii. event Target stage,

Iii. Event bubbles.

For example:

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

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

Event blister: starts from the target element and spreads to the top element. If a node is bound with corresponding event processing functions, these functions will be triggered once. To prevent event bubbles, use e. stopPropagation () (Firefox) or e. cancelBubble = true (IE) to organize event bubbling propagation.

Delegate functions in jQuery and Dojo
The following describes 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));});

The delegate method of jQuery requires three parameters: a selector, a time name, and an event handler.

Similar to jQuery, Dojo only differs in the programming style of the two:

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); });})

In dojox. NodeList, the delegate module of Dojo provides the same interface and parameters as jQuery.

Through delegation, you can experience the advantages of event Delegation for development:

1. Fewer functions are managed. You do not need to add a listener function for each element. For child elements of the same parent node that are similar to each other, the event can be handled by the listener function delegated to the parent element.

2. You can easily add and modify elements dynamically without modifying event binding because of element changes.

3. The association between JavaScript and DOM nodes is reduced, which reduces the probability of Memory leakage caused by cyclic references.

Use proxy in JavaScript programming
This section describes how to use the browser bubble mechanism to add event proxies to DOM elements when processing DOM events. In fact, in pure JS programming, we can also use this programming mode to create a proxy object to operate on the target object.

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 ();. getColor ();. setColor ("green");. getColor (); // call the proxy var d = delegate (a,. setColor); d ("blue"); // execute proxy. getColor (); // B. getColor ();

In the preceding example, the proxy function d created by calling the delegate () function is used to modify.

Although this method uses apply (call can also be used) to implement the transfer of the call object, it also hides some objects in programming mode, it can protect these objects from random access and modification.

In many frameworks, the concept of delegation is referenced to specify the running scope of a method.

Typical examples include dojo. hitch (scope, method) and createDelegate (obj, args) of ExtJS ).

The above is all the content of this article, and I hope it will help you learn javascript programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.