Home >Web Front-end >JS Tutorial >Detailed explanation of examples of event model in JS

Detailed explanation of examples of event model in JS

零下一度
零下一度Original
2017-06-26 11:29:511503browse

I was relatively clear about the event model before, and many concepts were clearly mapped in my mind. After working, on the one hand, I used
limitations, and on the other hand, I got used to using various event monitoring methods in the framework. Simplicity means convenience. Over time, some concepts of events began to fade out of my memory, just like I do now. I have begun to forget C language pointers, Maxwell's equations, matrix transformations, least squares method, etc. Knowledge is like colorful cobblestones paving the way forward, from simple to profound, from profound to understanding, always helping you go further and further. Let’s look back at the event model.


1. Brief introduction to events
Events include:Mouse eventsKeyboard events
Frame events onerror onresize onscroll Wait
Form event event onblur onfocus, etc
Clipboard event oncopy oncut onpaste
Print event onafterprint onbeforeprint
Drag event ondrag ondragenter etc.
media event onplay onpause
animation event animationend
Transition event
Other events, etc.

Events are encapsulated into objects, including
Target event object

Event listening object

Mouse event object
Keyboard event object, etc.
They contain their own properties and methods, and also inherit from the Event object. It depends on your W3C.
Commonly used methods:
event. preventDefault()//Prevent the default behavior of elements, such as link jumps and form submissions;
event. stopPropagation()//Prevent event bubbling


2. Three models of events

1. Original event model (DOM level 0)
Features: In the original event model, events There is no concept of propagation after occurrence, no event flow. When an incident occurs, handle it immediately. The listening function is just an attribute value of the element, and the listener is bound by specifying the attribute value of the element. There are two writing methods:
HTML: dfe8e6650259415a310b5c2a526a89f0
js : document.getElementsById('btn').onclick = func

Advantages: All browsers are compatible

Disadvantages:

a. There is no separation between logic and display;

b. Only one listening function for the same event can be bound, and then bound will overwrite the previous one.

c. Unable to pass event bubbling, delegation and other mechanisms.

In the current modular development of web programs and more complex logic, this method is obviously outdated, so it is not recommended in real projects. It is okay to write some demos at ordinary times, and the speed is faster.

2. IE event model

Features: IE sets the event object as the attribute of window in the processing function. Once the function execution is completed, it is set to null

. IE's event model has only two steps. First, the element's listening function is executed, and then the event bubbles along the parent node to the document. Method to bind and release the listening function:
attachEvent("eventType","handler"), where evetType is the type of event, such as onclick, be sure to add
’on’.
The method to deactivate the event listener is detachEvent("eventType", "handler" );
Disadvantage: It can only be used by IE itself, which is too cold.


3. DOM2 event model

The event model is standardized in W3C Level 2 DOM events, that is, the DOM2 event model. Modern browsers (not counting IE9 and below) all

follow this specification. Features: In the event model developed by W3C, the occurrence of an event includes three processes:
a. Event capture stage. The event is propagated from the document all the way down to the target element. During this process, the passing nodes are checked in turn to see whether the listening function for the event is registered, and if so, it is executed.
b. Event processing stage. When the event reaches the target element, the event processing function of the target element is executed.
c. Event bubbling stage. The event rises from the target element until it reaches the document. It also checks whether the passing nodes have registered
the listening function for the event, and executes it if so.


Note:
All event types will go through the event capture phase, but only some events will go through the event bubbling phase. For example, the
submit event will not be bubbled.

Method to bind and release the listening function: addEventListener("eventType", "handler", "true|false"); where eventType refers to the event type, note Do not add the 'on' prefix , different from that under IE.
The second parameter is the processing function,

The third parameter is used to specify whether to enter the capture phase true during the capture phase false only the bubbling phase

The release of the listener is also similar: removeEventListner("eventType", "handler","true!false");


Compatible with IE and modern browsers event registration listening writing method

var a = document.getElementById('XXX');
if(a.attachEvent){
    a.attachEvent('onclick',func);
}
else{//IE9以上和主流浏览器
    a.addEventListener('click',func,false);
}

现有的框架和类库都会对适应各种浏览器做兼容性的封装,JQuery底层即使用了上面的兼容性写法。

 

三、事件的捕获-冒泡机制
DOM2标准中,一次事件的完整过程包括三步:捕获→执行目标元素的监听函数→冒泡,在捕获和
冒泡阶段,会依次检查途径的每个节点,如果该节点注册了相应的监听函数,则执行监听函数。

以如下HTML结构为例子,执行流程应该是这样的:

<div id="parent">
       父元素
       <div id="child">子元素</div>
</div>

运行一下一目了然。

var parent= document.getElementById(&#39;parent&#39;);
	console.dir(parent);
    var child = document.getElementById(&#39;child&#39;);
    parent.addEventListener(&#39;click&#39;,function(){alert(&#39;父亲在捕获阶段被点

击&#39;);},true);//第三个参数为true
    child.addEventListener(&#39;click&#39;,function(){alert(&#39;孩子被点击了&#39;);},false);
 parent.addEventListener(&#39;click&#39;,function(){alert(&#39;父亲在冒泡阶段被点击

了&#39;);},false);//第三个参数为false

 

  可以看到,第三个即用来指定是否在捕获阶段进 true捕获阶段,false没有捕获阶段 。
如果不想让事件向上冒泡,可以在监听函数中调用event.stopPrapagation()来完成,后面会有应
用的栗子。

四、事件委托机制

  委托就是把事件监听函数绑定到父元素上,让它的父辈来完成事件的监听,这样就把事情“委托
”了过去。在父辈元素的监听函数中,可通过event.target属性拿到触发事件的原始元素,然后
再对其进行相关处理。

 

五、jQuery中的事件监听方式
  jQuery中提供了四种事件监听方式,分别是bind、live、delegate、on,对应的解除监听的
函数分别是unbind、die、undelegate、off。这几个方法已经对各种浏览器的兼容性进行封装。
具体方法可以查看手册。
   注意几点:
   jQuery推荐事件的绑定都使使用on方法
   jQuery默认事件不在捕获中进行

六、什么是自定义事件
张鑫旭的《js-dom自定义事件》


七、一个简单例子
点击弹窗之外任何地方,弹框关闭。


方法:给body绑定事件,在事件的执行函数里关闭弹框;
     给弹框元素绑定点击事件,在事件的执行函数里面组织事件冒泡,即:
     event.stopPrapagation();

 

The above is the detailed content of Detailed explanation of examples of event model in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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