I. Event transmission mechanism

To learn more about delegates, it’s best to understand the event propagation mechanism:

We divide events into three phases: capture phase, target phase, and bubble phase.

  1. Capture phase: When clicking, go through the capture phase and find the target from the outermost layer such as HTML (compatibility is not considered here)
  2. Target phase: After the target phase, events are responded to
  3. Bubble phase: Trigger the same event method layer by layer from clicking on the target until the outermost layer (root node)

When an event (click event) of the current element is triggered, not only the current element’s event behavior is triggered, but also the related event behavior of its ancestors is triggered in turn. This mechanism is called “event bubbling propagation mechanism”.

As shown in figure:

If you do not understand, you can see this small 🌰 oh 😯 :

For example, one day you are playing in the river, walking, you see a small stone, hum, throw a small stone into the river, the river made layers of waves. This is called bubbling.

Two, the event chestnut (bubbling)

chestnuts

<div id="parent">
	<div id="child">button</div>
</div>
<script>
	const parent=document.getElementById('parent');
	const child=document.getElementById('child');
	parent.addEventListener('click'.function(){
		console.log('parent');
	})
	child.addEventListener('click'.function(){
		console.log('child');
	})
	// After the above analysis, it is easy to get the result
</script>
Copy the code

Note that dom0 and DOM2 have different event mechanisms;

Dom0: mount on a property, the same element can have only one click event, multiple click events, the latter will overwrite the former;

Dom2: in eventTarget. prototype, multiple clicks on the same element will not be overwritten and will be executed. The principle is that there is a unified event pool; When triggered, the browser emits all events in the event pool in the order they are stored

I don’t want to say too much la la la la la la la, it’s a little off topic

Iii. Advantages of delegation (classic example)

1. Reduce memory consumption

Because the more binding events, the larger the browser memory footprint, serious impact on performance or take 🌰 :

  • There are 100 data, 100 Li, adding events to each li takes up a lot of memory, so, using the bubble mechanism, add click events to the parent element
<ul id="ul">
</ul>
<script>
	const ul=document.getElementById('ul');
	for(let i=0; i<100; i++){let li=document.createElement('li');
		li.innerHTML=i;
		ul.appendChild(li);
	}
	ul.addEventListener('click'.function(e){
		if(e.target.tagName==='UL') return;
		e.target.className=e.target.className.indexOf('color') = = =- 1?'color':' ';
	})// Can execute by itself; Color is the name of the class. You can add your favorite color to the style
</script>
Copy the code

2. With the advent of Ajax, local refreshes are prevalent, causing events to be rebound each time they are loaded (using setTimeout asynchronously instead).

<ul id="ul">
	<li>666</li>
</ul>
<script>
	const ul=document.getElementById('ul');
	const lists=ul.getElementsByTagName('li');
	setTimeout((a)= >{
		for(let i=0; i<100; i++){let li=document.createElement('li'); li.innerHTML=i; ul.appendChild(li); }},400)
	for(let i=0; i<lists.length; i++){ lists[i].onclick=function(){ alert(i); }}// only 666 popover is clicked; How to solve; Use your brain; I believe you are the best
</script>
Copy the code

4. Limitations of entrustment

  1. For example, events such as Focus and blur have no event bubble mechanism, so they cannot be delegated.
  2. Although events such as Mousemove and Mouseout have bubbled, they can only be calculated and positioned by location, which is high in performance and therefore not suitable for event delegation.

5. Notice items using delegate (can be called application items)

  1. Use event delegates only where necessary, such as in ajax’s local refresh area
  2. Minimize the level of binding and do not bind on the body element. (The principle of event delegation is inseparable from DOM search; Too many layers of lookup in a browser can be very performance - consuming)
  3. Reduce the number of bindings, if possible, by combining multiple event bindings into a single event delegate to be distributed by the event delegate’s callback.

Classic interview questions

What’s the difference between a Mouseeneter and a mouseover?

inner.onmouseenter = function () {
    console.log('inner enter');
};
outer.onmouseenter = function () {
    console.log('outer enter');
};
inner.onmouseleave = function () {
    console.log('inner leave');
};
outer.onmouseleave = function () {
    console.log('outer leave');
};
Copy the code

Explanation:

  1. Over is an event that slides from the parent element into the child element. It is an event that leaves the parent element, triggering out of the parent element and triggering over of the child element. Enter is entering, going from the parent to the child, not leaving the parent, not triggering leave, triggering Enter of the child
  2. Enter and leave prevent bubbling propagation of events, while over and out also have bubbling propagation

Therefore, in the case of parent element nesting child element, there will be a lot of unwillingness to operate when using OVER. In this case, it will be easier to use ENTER. Therefore, in real projects, ENTER will be used more than OVER

Compatibility is not involved in this article, 8 discount ️ should be added when time is available