Events have been one of the most powerful objects in JavaScript. JavaScript provides AddEventListener and attachevent two ways to bind events to DOM nodes, and jquery is further encapsulated to provide a bind method that is compatible with each browser. Now, this traditional way of event binding has the following disadvantages:
1. You may need to bind a lot of eventhander.
If a table in the page has 100 rows, you must now bind a click event for each row. Then you have to bind 100 EventHandler, which is a huge burden on page performance, because more memory needs to be created to hold these handler.
2. The event cannot be bound after the DOM node is added.
If the code in the page is as follows:
$ ("#dv"). Bind (' click ', function () {alert (' Test ');});
$ (body). Append (' <div id= ' dv >test</div> ')
After adding the DIV is unable to trigger the click event.
to address these two issues, JavaScript introduces an event proxy. First, let's look at the bubbling mechanism in JS.
Basically, all browsers support event bubbling. When an event is triggered on a DOM node, the event is passed up to the root node of the document. Since all of the node's events will eventually be passed to the document root node, if we bind the event directly to the document root node, and then event.target to determine which node triggered the event, is it a lot less eventhandler binding?
The live method in jquery is formally implemented according to this principle, so let's implement a live simple version:
In the live method, the event is bound on the document node, $ (event.target). closest (that) to match the element that actually triggered the event. In the demo, we've bound the click event for each TD we joined, and we've clicked on a different TD, and we've found that they'll pop up their text box.
The live method compensates for two shortcomings of the previously mentioned traditional event binding approach. But the live method still has its shortcomings. Look at this code:
$ ("#tb TD"). Mylive (' click ', Function (event) {
alert (Event.target.innerHTML);
});
It will first traverse the entire document based on the jquery selector, find all the #tb TD elements, and store them as objects. However, in the implementation of live, these objects are not exploited, but simply matching the "#td TD" as a string to the event source. This greatly increases a lot of unnecessary consumption.
So is there a way to improve the situation? The delegate proxy method is provided in jquery, which supports binding events to the specified element, not just the document. Knowing how it works, let's implement a delegate simple version:
The Mydeletage method does not need to get all the TD objects, but only the Div object that gets the bound event. This is better than the live method in execution efficiency.
Event proxies in JavaScript