Home > Article > Web Front-end > Analysis of events in javascript (details)
The content of this article is about the analysis of events in JavaScript (detailed). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
JavaScript programs adopt an asynchronous event-driven programming (Event-driven programming) model. Wikipedia explains it as:
Event-driven programming (Event-driven programming) is a computer programming model. The program running process of this model is determined by user actions (such as mouse button presses, keyboard key press actions) or messages from other programs. Compared with batch programming, the flow of program execution is determined by the programmer. Batch programming is a method used in introductory programming instruction courses. However, the design model of event-driven program design was born in the context of interactive programs.
In short, in web front-end programming, JavaScript uses the event model API and event model provided by the browser. User interaction, receiving user input.
Because the user's behavior is uncertain. This scenario cannot be solved by the traditional synchronous programming model, because you cannot wait for the user to complete the operation before executing the subsequent code. Therefore, asynchronous events are used in javascript, that is to say: Events in js are all executed asynchronously.
The basic implementation principle of the event driver model is basically the use of event loop (Event Loop). This part involves the browser event model and callback principle.
In the JavaScript DOM and BOM models, APIs such as setTimeout and XMLHTTPRequest are also asynchronous and are not native to the JavaScript language itself.
There are three methods of event binding:
Directly set on the DOM element on eventType
Bind event handler. For example:
<a>点击我</a>
This method has two disadvantages:
Event handlers and HTML structures are mixed together, which does not comply with the MVX specification. To keep content, presentation, and behavior separate, we should avoid writing this way.
The code written in this way has global scope and may cause naming conflicts, leading to unforeseen serious consequences.
Use the on eventType attribute API on the DOM Element
var el = getElementById('button'); //button是一个<button>元素 el.onclick = function(){ alert('button clicked.') }; el.onclick = function(){ alert('Button Clicked.') }; //实际之弹出'Button Clicked.',函数发生了覆盖</button>
This method also has a disadvantage : The function bound later will overwrite the previous function. For example, if we register a window.onload event, it may overwrite an existing event function in a library. Of course, there can be a solution to this:
function addEvent(element, EventName, fun) { //EventName = 'on' + eventType var oldFun = element[EventName]; if (typeof oldFun !== 'function') { element[EventName] = fun; } else { element[EventName] = function() { oldFun(); fun(); }; } } addEvent(window, "onload", function() { alert('onload 1') }); addEvent(window, "onload", function() { alert('onload 2') });
Of course, under normal circumstances, it is enough to use DOM Ready, because JavaScript can be executed after the DOM is loaded
There are two standard binding methods. addEventListener and attachEvent. The former is an API supported by standard browsers, and the latter is an API supported by browsers below IE8:
//例如给一个button注册click事件 var el = getElementById('button'); //button是一个<button>元素 if(el.addEventLister){ el.addEventListener("click", function(e){ alert("button clicked."); },false); } if(el.attachEvent){ el.attachEvent("onclick", function(e){ alert("button clicked."); }); }</button>
It should be noted that:
The first parameter event type of addEventLister is not prefixed with on, but the on prefix is required in attachEvent.
This in the event callback function in addEventLister points to the event element target itself, while this in the event callback function in attachEvent points to the window.
addEventLister has a third parameter, true indicates that the event is working in the capture phase, false indicates the bubbling phase (default value: false). And attachEvent can only work in the bubbling stage.
Run the following code in chrome:
<a>click me</a> <script> var link = document.getElementById('link'); link.onclick = function() { alert(3); }; //覆盖了行内的onclick定义 link.addEventListener('click', function() { alert(4); },false); link.addEventListener('click', function() { alert(5); },false); </script>
The pop-up sequence after clicking is: 3 -> 4 -> 5 -> 1
The 4th line of code here covers the onclick definition within the line. If this line is commented, the input sequence is: 2 -> 4 -> 5 -> 1, and no overwriting will occur between addEventListener.
For the first two methods mentioned above, to unbind event, you only need to set the corresponding event function to null:
var el = document.getElementById('button'); el.onclick = null;
For the third method above, use the removeListen() method. In IE8, use detachEvent() accordingly. Note that they correspond to the above registration methods one-to-one and cannot be mixed.
//这是一段错误代码,不能实现事件移除 //建立一个事件 var el = document.getElementById('button'); //button是一个<button>元素 if(el.addEventLister){ el.addEventListener("click", function(e){ alert("button clicked."); },false); } if(el.attachEvent){ el.attachEvent("onclick", function(e){ alert("button clicked."); }); } //试图移除这个事件 if(el.removeEventLister){ el.addEventListener("click", function(e){ alert("button clicked."); },false); } if(el.detachEvent){ el.datachEvent("onclick", function(e){ alert("button clicked."); }); } //移除失败</button>
The above error is that when the event function is defined in this way, although it looks exactly the same, the address in the memory is different. In this way, the computer will not think that the released and bound functions are the same function, and naturally it will not be released correctly. It should be written like this:
//建立一个事件 var el = document.getElementById('button'); //button是一个<button>元素 var handler = function(e){alert("button clicked.");}; if(el.addEventLister){ el.addEventListener("click", handler,false); } if(el.attachEvent){ el.attachEvent("onclick", handler); } //试图移除这个事件 if(el.removeEventLister){ el.addEventListener("click", handler, false); } if(el.detachEvent){ el.datachEvent("onclick", handler); } //移除成功</button>
I mentioned before that the third parameter of the addEventListener function represents capture and bubbling. This is an important point!
Let me describe their definition myself:
Bubbling: An event triggered on an element will be triggered from the inside to the outside on the parent element of this element. This event is triggered until the window element.Capture: When an event is triggered on an element, the event is triggered on all sub-elements of each layer of this element, and goes inward layer by layer until all elements no longer have sub-elements. .
As shown below (note: the picture comes from Baidu search)
事件间回到函数参数是一个事件对象,它里面包括许多事件属性和方法,比如,我们可以用以下方式阻止冒泡和默认事件:
//该例子只写了handler函数 function handler(event) { event = event || window.event; //阻止冒泡 if (event.stopPropagation) { event.stopPropagation(); //标准方法 } else { event.cancelBubble = true; // IE8 } //组织默认事件 if (event.perventDefault) { event.perventDefault(); //标准方法 } else { event.returnValue = false; // IE8 } }
其次,普通注册事件只能阻止默认事件,不能阻止冒泡
element = document.getElemenById("submit"); element.onclick = function(e){ /*...*/ return false; //通过返回false,阻止冒泡 }
事件函数中有一个参数是事件对象,它包含了事件发生的所有信息,比如键盘时间会包括点击了什么按键,包括什么组合键等等,而鼠标事件会包括一系列屏幕中的各种坐标和点击类型,甚至拖拽等等。当然,它里面也会包括很多DOM信息,比如点击了什么元素,拖拽进入了什么元素,事件的当前状态等等。
这里关于事件兼容性有必要强调一下:
document.addEventListener('click', function(event) { event = event || window.event; //该对象是注册在window上的 console.log(event); //可以输出事件对象看一看, 属性很多很多 var target = event.target || event.srcElement; //前者是标准事件目标,后者是IE的事件目标 },false);
关于鼠标事件坐标的问题,可以看另一篇博客:元素和鼠标事件的距离属性
除了用户操作以外,我们也可以写代码主动触发一个事件,以ele元素的click事件为例:
ele.click(); //触发ele元素上的单击事件
有时候我们需要给不存在的的一段DOM元素绑定事件,比如用户动态添加的元素,或者一段 Ajax 请求完成后渲染的DOM节点。一般绑定事件的逻辑会在渲染前执行,但绑定的时候找不到元素所以并不能成功。
为了解决这个问题,我们通常使用事件代理/委托(Event Delegation)。而且通常来说使用 事件代理的性能会比单独绑定事件高很多,我们来看个例子。
传统注册事件方法,当内容很多时效率低,不支持动态添加元素
事件委托注册方法,不论内容有多少都只注册1次,支持动态添加元素:
很明显,处理浏览器兼容太麻烦了,所以这里把js中的事件注册相关函数封装一下,作为整理。
//均采用冒泡事件模型 var myEventUtil={ //添加事件函数 addEvent: function(ele, event, func){ var target = event.target || event.srcElement; if(ele.addEventListener){ ele.addEventListener(event, func, false); } else if(ele.attachEvent) { ele.attachEvent('on' + event, func); //func中this是window } else { ele['on' + event] = func; //会发生覆盖 } }, //删除事件函数 delEvent:function(ele, event, func) { if(ele.removeEventListener){ ele.removeEventListener(event, func, false); } else if(ele.detachEvent) { ele.detachEvent('on' + event, func); } else { ele['on' + event] = null; } }, //获取触发事件的源DOM元素 getSrcElement: function(event){ return event.target || event.srcElement; }, //获取事件类型 getType: function(event){ return event.type; }, //获取事件 getEvent:function(event){ return event || window.event; }, //阻止事件冒泡 stopPropagation: function(event) { if(event.stopPropagation) { event.stopPropagation(); } else { event.cancelBuble = false; } }, //禁用默认行为 preventDefault: function(event){ if(event.preventDefault){ event.preventDefault(); } else { event.returnValue = false; } } };
需要注意的是: JQuery中的事件都工作在冒泡阶段,且只能工作在冒泡阶段
方法一:
//不会发生覆盖,但不利于解除,不能动态操作事件 <button>here</button> $("#button").click(function(){ //注册一个click事件,当然可以用其他事件名的函数注册其他事件 console.log("clicked"); });
方法二:
//不会发生覆盖,利于解除,不能动态操作事件 <button>here</button> //注册一个事件 $("#button").bind("click", function() { //注册一个click事件,当然可以用其他事件名的函数注册其他事件 console.log("clicked"); }); //当然还可以这样写,给事件指定命名空间 $(document).bind('click.handler1', function() { console.log(1);}) $(document).bind('click.handler2', function() { console.log(2);}) //解除一个事件 $("#button").unbind(".handler1"); //解除元素上所以handler1命名空间中的事件 $("#button").unbind('click.handler2'); // 解除元素上的click.handler2事件 $("#button").unbind('click'); // 解除元素上所有点击事件 $("#button").unbind() // 解除元素上所有事件 //bind()方法还介受3个参数形式,这里就不赘述了,感兴趣可以自己看看相关资料。
方法三:
//不会发生覆盖,但不利于解除,能动态操作事件,依赖于事件冒泡 //注册事件 $(document).delegate(".item", "click", function(){console.log(this.innerHTML);}); //第一个是选择器, 第二个是事件类型, 第三个是事件函数 //移除事件 $(document).undelegate(".item", "click", handler); //移除元素上指定事件 $(document).undelegate(".item", "click"); //移除元素上所有click事件 $(document).undelegate(".item"); //移除元素上所有事件
方法四:
//不会发生覆盖,但不利于解除,能动态操作事件,不依赖于事件冒泡 //注册事件 #(".item").live("click", function(){console.log(this.innerHTML);}) //第一参数是事件类型, 第二参数是事件函数 //移除事件 $(".item").die("click", handler); //移除元素上指定click事件 $(".item").die("click"); //移除元素上所有click事件
两个简化方法:
//hover方法 $("#button").hover(function(){ //鼠标移入时的动作,不冒泡 }, function(){ //鼠标移出时的动作,不冒泡 }); //toggle方法 $("#button").toggle(function(){ //第一次点击时的动作 }, function(){ //第二次点击时的动作 }, .../*可以放多个函数,依次循环响应*/);
//不能触发addEventListener和attachEvent //主动触发一个事件 $("#button").trigger("click"); //触发所有click事件 $("#button").trigger("click.handler1"); //触发所有click.handler1事件 $("#button").trigger(".handler1"); //触发所有handler1命名空间的事件 $("#button").trigger("click!"); //触发所有没有命名空间的click事件 $("#button").trigger(event); //在该元素上触发和事件event一样的事件 $("#button").trigger({type:"click", sync: true}); //触发click事件,同步
相关推荐:
JavaScript事件类型中UI事件详解_javascript技巧
The above is the detailed content of Analysis of events in javascript (details). For more information, please follow other related articles on the PHP Chinese website!