An initial look at event proxies in javascript

  • 2020-03-30 02:18:31
  • OfStack

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 provides further encapsulation and provides a bind method that is compatible with all browsers. Now, this traditional event binding approach has the following disadvantages:

1. Many EventHander bindings may be required.

If a table on the page has 100 rows, you must now bind a click event for each row. Then you have to bind 100 eventhandlers, which is a huge burden on page performance because you need to create more memory to hold these handlers.

2. The DOM node added after the event cannot be bound.

Suppose the code on the page looks like this:


$("#dv").bind('click',function(){alert('test');});
$(body).append('<div id="dv">test</div>')

The div added after this cannot trigger the click event.

To solve both problems, javascript introduces an event proxy. First, let's look at the bubbling mechanism in js.

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201403/20140308094138.png ">


Jquery's live method is implemented according to this principle. Let's implement a simple version of live:


$.fn.mylive=function(eventType,fn){
 var that=this.selector;
 $(document).bind(eventType,function(event){
  var match=$(event.target).closest(that)
  if(match.length !== 0){
   fn.apply($(event.target),[event]);
  }
 })
}
$("#tb td").mylive('click',function(event){
 alert(event.target.innerHTML);
});
var tb='<table id="tb"> 
  <tr> 
   <td>the first column</td>
   <td>the second column</td>
   <td>the third column</td>
  </tr>
</table>';
$("body").append(tb);

Live method, the event on the document node, $(event. The target). The closest (that) to match the real trigger element. In the demo, we bound the click event to each subsequent td, and when we clicked on different td, we found that a prompt for Text would pop up for them.

The live approach makes up for two shortcomings of the traditional event binding approach mentioned earlier. However, the live method still has its disadvantages. Look at this code:


$("#tb td").mylive('click',function(event){
 alert(event.target.innerHTML);
});

It will first walk through the document according to the jquery selector, find all the # TB td elements, and store them as objects. However, in live's implementation, these objects are not utilized, and "#td td" is simply used as a string to match the event source. This adds up to a lot of unnecessary consumption.

Here is just a starting point, let you understand the principle of event proxy, jquery in the live and delegate implementation is much more complex.


Related articles: