In Javasript, proxies and delegates often appear.
So what kind of situation is it used? What is the principle of it?
Here is a description of the usage and principles of JavaScript delegate, as well as delegate interfaces in frameworks such as Dojo,jquery.
JavaScript Event Agent
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 event bubbling mechanism of the browser, let's give a concrete 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 UL parent node that contains a number of the children 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 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 we need to trigger the corresponding handling event when an Li is clicked.
Our usual writing is to add an event listener 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 element in this UL is added or deleted frequently, we need to call this Addlistenersli method every time we add Li to add an event handler for each Li node.
This can result in the complexity of adding or removing procedures and the likelihood of errors.
The problem-solving approach is to use the event broker mechanism, and when the event is thrown to a higher parent node, we check the event's target object to get the event source, Li.
The following code can accomplish the desired effect:
/Gets the parent node and adds a click event
document.getElementById ("list") to it. AddEventListener ("click", Function (e) {
// Check if the event source E.targe is Li
if (e.target && e.target.nodename.touppercase = = "Li") {
//
//todo
Console.log ("List item", E.target.id, "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, judge the E.target.nodename to see if it is the node we need to handle. And got the clicked Li node through the e.target. So that the corresponding information can be obtained and processed.
Event bubbling and capturing
The event bubbling mechanism of the browser, for the capture and processing of events, different browser vendors have different processing mechanisms, here describes the DOM2.0 definition of the standard event.
The DOM2.0 model divides the event handling process into three phases:
First, the event capture phase,
Second, the target phase of the event,
Third, the foaming stage of the event.
The following figure:
Event capture: When an element triggers an event (such as onclick), the top-level object document emits an event stream that flows from the node of the DOM tree to the target element node until the target element in which the event actually occurs is reached. 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 for the target element is executed. If there is no binding listener function, it is not executed.
Event bubbling: Starting from the target element, propagating to the top-level element. On the way if there are nodes bound to the corresponding event handler functions, these functions are triggered one at a time. If you want to prevent bubbling of events, you can use E.stoppropagation () (Firefox) or e.cancelbubble=true (IE) to organize bubbling propagation of events.
Delegate functions in jquery and Dojo
Let's look at the usage of the event agent interface provided in Dojo and jquery.
Jquery:
$ ("#list"). Delegate ("Li", "click", Function () {
//"$ (This)" is the node of that's 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 function.
Dojo, like jquery, is only a difference 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 of that ' is clicked
console.log (' You clicked a link! ', this);
});
The delegate module of Dojo, in Dojox.nodelist, provides the same interface as jquery, with the same parameters.
By delegating, you can appreciate several benefits of using event delegates for development:
1. The function of management becomes less. You do not need to add a listener function for each element. For child elements similar to the same parent node, the event can be handled by a listener function that is delegated to the parent element.
2. You can easily add and modify elements dynamically, and you do not need to modify event bindings because of element changes.
There is less association between 3.JAVASCRIPT and DOM nodes, which reduces the probability of memory leaks that occur due to circular references.
Using proxies in JavaScript programming
The above describes the use of browser bubbling mechanism to add event proxies to DOM elements when dealing with DOM events. In fact, in the pure JS programming, we can also use this programming mode, to create a proxy object to manipulate 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 ();
A.getcolor ();
A.setcolor ("green");
A.getcolor ();
Call Agent
var d = Delegate (A, a.setcolor);
D ("Blue");
Executive Agent
A.getcolor ();
B.getcolor ();
In the example above, the modification to a is manipulated by calling the proxy function D created by the delegate () function.
This approach, although using apply (call can also) to achieve the transfer of the invocation object, but from programming mode to achieve the hidden objects, you can protect these objects are not casually accessed and modified.
The concept of a delegate is referenced in many frameworks to specify the running scope of the method.
The CreateDelegate (Obj,args) of Dojo.hitch (Scope,method) and ExtJS are more typical.
The above is the entire content of this article, I hope to learn JavaScript program to help you.