Delegation matter delegate or agent

Source: Internet
Author: User

In Javasript delegate the word often appears, see the literal meaning, the agent, the delegate. So what kind of situation is it used in? What is the principle of it? Delegate-related interfaces are often seen in various frameworks. What are the special uses of these interfaces? This article focuses on the use and principles of JavaScript delegate, and the interfaces delegate in frameworks such as Dojo,jquery. The JavaScript Event agent first describes the JavaScript event proxy. 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 events to their parent node and delegating the event to the parent node. This is mainly due to the browser's event bubbling mechanism, which is described in detail later. Let's take a specific example to illustrate how to use this feature. This example is mainly taken from the related article of David Walsh (how JavaScript Event delegation Works). Suppose there is a UL parent node that contains many of the Li's child nodes:
<ul id= "Parent-list" >  <li id= "post-1" >item 1</li> <li  id= "post-2" >item 2</li>  <li id= "post-3" >item 3</li>  <li id= "post-4" >item 4</li> <li  id= "Post-5" > Item 5</li>  <li id= "post-6" >item 6</li></ul>

When we move the mouse over Li, we need to get information about this Li and float out of the window to show the details, or when an li is clicked, the corresponding processing events need to be triggered. Our usual notation is to add some kind of event listener like 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 i=0, l = linodes.length; i < L; i++) {        addlisteners4li (linodes[i]);    }   }

If the LI element in this UL is frequently added or deleted, we need to call this addlisteners4li method each time we add Li to add an event handler for each Li node. This adds complexity and the likelihood of errors.

The simpler approach is to use the event broker mechanism, and when the event is thrown to the parent of the higher layer, we judge and get the event source Li by examining the target object (target) of the event. The following code can accomplish the effect we want:

Gets the parent node and adds a click event document.getElementById ("Parent-list") to it. AddEventListener ("click", Function (e) {  // Check if the event source E.targe is an Li  if (e.target && e.target.nodename.touppercase = = "Li") {    //The real process is here    Console.log ("List item", E.target.id.replace ("post-"), "was clicked!");}  });

Adds 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 is judged by the e.target.nodename to determine whether it is the node we need to process. And got the clicked Li node through e.target. So that the corresponding information can be obtained and processed.

Event bubbling and capturing

The event bubbling mechanism of the browser has been mentioned in the previous introduction. Here is a detailed description of the browser's process of handling DOM events. For the event capture and processing, different browser vendors have different processing mechanisms, here we mainly introduce the DOM2.0 definition of the standard event.

The DOM2.0 model divides the event processing process into three stages: first, the event capture phase, the event target phase, and the event bubbling stage.

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

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

Event bubbling: Starts at the target element and propagates toward the top level element. On the way, if a node is bound to a corresponding event handler, these functions are triggered at once. If you want to block event blistering, you can use E.stoppropagation () (Firefox) or e.cancelbubble=true (IE) to organize the bubbling propagation of events.

Delegate functions in jquery and Dojo

Here's how to use the event broker interface provided in Dojo and jquery.

The first is jquery:

$ ("#link-list"). Delegate ("A", "click", Function () {  //"$ (this)" are the node that's clicked  Console.log ("You Clicked a link! ", $ (this));});

JQuery's delegate method requires three parameters, a selector, a time name, and an event handler function.

And dojo, like jquery, is just the difference between the two programming styles:

Require (["Dojo/query", "dojox/nodelist/delegate"], function (query,delegate) {    query ("#link-list"). Delegate ("A "," onclick ", function (event) {    //" This.node "is the node of the clicked    Console.log (" You clicked a link! ", this) ;  });})

Dojo's delegate module, in Dojox.nodelist, provides the same interface as jquery, with the same parameters.

Advantages

With the introduction above, you should be able to appreciate several advantages of using event delegation for Web applications:

1. The function of management has become less. You do not need to add a listener function for each element. For a child element similar to the same parent node, the event can be handled by delegating a listener function to the parent element.

2. You can easily add and modify elements dynamically, without modifying the event bindings because of changes to the elements.

There is less association between 3.JAVASCRIPT and DOM nodes, which reduces the probability of a memory leak due to circular references.

Writing here, I suddenly remembered the confusion about the dojo DataGrid before: So many rows and cells, how to deal with the relationship between their events. Now think about it, it's easy to use a delegate. All events are delegated to the outermost node of the grid, and some methods are used to get and add additional properties of the event when the event occurs, such as rowindex, CellIndex, and then on a handler function assigned to Onrowclick,oncellclick.

Using proxies in JavaScript programming

Described above is the use of the browser bubbling mechanism to add event proxies to 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 the Masaki 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 ("Done! ");    A.getcolor ();

In the example above, the modification of a is manipulated by invoking the agent function D created by the delegate () function. This approach, although using apply (call can), implements the transfer of the calling object, but hides some objects from the programming schema, protecting them from random access and modification.

The concept of delegation is referenced in many frameworks to specify the run scope of the method. More typical createdelegate (Obj,args) such as Dojo.hitch (Scope,method) and ExtJS. Interested students can take a look at their source code, mainly the JS function of the Apply method to develop the scope of execution.

Delegation a thing delegate or proxy

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.