Home > Web Front-end > JS Tutorial > In-depth analysis of Javascript event proxy_Basic knowledge

In-depth analysis of Javascript event proxy_Basic knowledge

WBOY
Release: 2016-05-16 15:16:55
Original
955 people have browsed it

For a long time, I have always felt that there is no difference between the occurrence of an event and the arrival of the event.

Recently, I took another look and found that the difference is really not that big! Let’s see how you understand it.

To understand what an event agent is, you need to first understand what an agent is.

From a business point of view, an agent is: I have the goods, you don’t have the goods, but I don’t have the time or energy to sell them all, and you have so much free time that you only have time. So, I entrust you to help me buy it, and then I will give you a commission. In this process, you actually have the goods.

OK, how do you understand the meaning of the term event agent literally? More on this later.

1 Let’s first look at a real example of a novice binding onclik events

If I followed my previous behavior, how would I add onlick to each li tag? Nonsense, if it were me, it would definitely be simple and crude.
Loop through each li and then bind them all onlick.

So my code should look like this:

<ul id="thl">
  <li>001</li>
  <li>002</li>
  <li>003</li>
</ul>

<script>
  var thl= document.getElementById('thl');
  var aLi = thl.getElementsByTagName('li');
  for (var i = 0; i < aLi.length; i++) {
    aLi[i].onclick = fn;
  }
  
  function fn (){
   console.log("maomaoliang");
  }
</script>

Copy after login

It seems like everything is fine. Although some articles say that this consumes performance, my computer is good and I don’t care about your performance, so I can’t take it too seriously.

2 Suddenly one day, I found that the new li added through js was not bound to onlcik

var node=document.createElement("li");
var textnode=document.createTextNode("maomaoliang");
node.appendChild(textnode);
document.getElementById("ul1").appendChild(node);
Copy after login

Then, when I click maomaoliang, it does not bind my onlick. Why is this?
Oh, it turns out that my original li and the li generated later did not happen at the same time. Before the new li element was created, events were added to the existing li. Okay, so annoying.

Three How to break it?

Then, I read some articles and found out that there is something called event proxy that can be used. I'll give it a try! So I rewrote part of the code, like this:

var thl= document.getElementById('thl');
thl.onclick = function(ev) {
  ev = ev || event;
  //兼容处理
  var target = ev.target || ev.srcElement;
  //找到li元素
  if (target.nodeName.toLowerCase() == 'li') {
     fn();
   }
};

function fn (){
 console.log("maomaoliang");
}

Copy after login

As a result, clicking on the new li also triggered the fn function. Well, as a body driven by curiosity, how could I not ask for more explanation? You still have to be more practical and understand the mystery behind it.

So, I looked at the information of the event agent.

First of all, you need to know what event bubbling is: when an event on an element is triggered, for example, the mouse clicks a button, the same event will be triggered in all ancestor elements of that element. This process is called event bubbling.

Then, back to the previous question "How to understand the meaning of the term event agent literally", who agented the event? Or who does the event represent?
Taking the example of this article, looking at the modified code, I bound the onlick event to the ul tag instead of the li tag. So, when I click on any li tag (whether it is dynamically generated or existing before), this event is like a bubble, popping up and popping up. Under normal circumstances, ul will also be bound to onclick, and body will also be bound to onclick, which means it will bubble to the root-most element. But I have bound onlick to ul here, so at this time, ul will intercept the bubble, the event will stop rising, and the body tag cannot be reached.

Then, var target = ev.target || ev.srcElement; This sentence is equivalent to telling me who I clicked on and who is the target. If this target happens to be the li tag if (target.nodeName.toLowerCase() == 'li'), then execute the fn function.

Finally, I proudly answered that question: table represents the onlick event!

4 Recall the steps of event proxy

Parent element binding event
The parent element knows who the actual target of the event is
We need to judge the target. If it is the element we need, a callback function will occur (so we must learn how to use selectors)

5 Final summary, two major benefits of event agency

Performance was accidentally optimized
Dynamically added elements can also be bound to events

Six things to note are

The above is for native js event binding, if you use jquery. And changed the code to the following:

/*var thl= document.getElementById('ul1');
thl.onclick = function(ev) {
  ev = ev || event;
  //兼容处理
  var target = ev.target || ev.srcElement;
  //找到li元素
  if (target.nodeName.toLowerCase() == 'li') {
     //li添加的事件
     fn();
   }
};*/

var node=document.createElement("li");
var textnode=document.createTextNode("maomaoliang");
node.appendChild(textnode);
document.getElementById("ul1").appendChild(node);

function fn (){
 console.log("maomaoliang");
}

$("#ul1").click(function(){
  fn();
});

Copy after login

In this way, the newly added li tag can also be tied to click. Isn’t it very convenient and simple? Do you feel that learning js is useless?

Haha, it’s normal to think like this. I used to think so too, but after making some things, I found that jquery is really not enough! But it’s basically enough!

Although the masters say that you need to learn js, I still think you can learn jquery first, and then learn js later, and the effect will be good.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template