Home >Web Front-end >JS Tutorial >A preliminary study on event proxy in javascript_javascript skills
Events have always been one of the most powerful objects in JavaScript. JavaScript provides two methods, addEventListener and attachEvent, to bind events to DOM nodes. jquery further encapsulates them and provides a bind method compatible with various browsers. Looking at it now, this traditional event binding method has the following shortcomings:
1. You may need to bind a lot of EventHanders.
If a table in the page has 100 rows, a click event must be bound to each row. Then 100 EventHandlers must be bound, which is a huge burden on page performance because more memory needs to be created to store these Handlers.
2. Events cannot be added after binding to DOM nodes.
Suppose the code in the page is as follows:
In order to solve these two problems, JavaScript introduced event proxy. First, let’s understand the bubbling mechanism in js.
Basically all browsers support event bubbling. When an event is triggered on a DOM node, the event will be propagated all the way up to the root node of the document. Since all node events will eventually be delivered to the document root node, if we directly bind the event to the document root node (document node), and then use event.target to determine which node triggered the event, will it reduce a lot of EventHandlers? What about the binding?
The live method in jquery is officially implemented based on this principle. Let’s implement a simple version of live:
$("#tb td").mylive('click',function(event){
alert(event.target.innerHTML);
});
var tb='
the first column | the second column td> | the third column |
The live method makes up for the two shortcomings of the traditional event binding method mentioned earlier. But the live method still has its shortcomings. Look at this code:
So is there any way to improve this situation? The delegate proxy method is provided in jQuery, which supports binding events to specified elements, not just documents. Understand its principle, let's implement a simple version of delegate:
$.fn.mydelegate=function(selector,eventType,fn){
$(this).bind(eventType,function(event){
var match=$(event.target).closest( selector);
if(match.length !== 0){
fn.apply($(event.target),[event]);
}
});
}
$("#dv").mydelegate('td','click',function(event){
alert(event.target.innerHTML);
});
var tb='
the first column | the second column td> | the third column |
This is just an introduction to let everyone understand the principle of event proxy. The implementation of live and delegate in jquery is much more complicated.