- 浏览: 304364 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (243)
- Core Java (13)
- Java (12)
- Android (2)
- Lucene (3)
- J2EE (3)
- Hibernate (2)
- Jsp & Servlet (3)
- Struts2 (3)
- Spring (5)
- JSF (6)
- RichFaces (2)
- HTML & JS & DOM & CSS (87)
- browser (1)
- Ajax & A4J (2)
- Workflow (1)
- Maven (3)
- Linux (2)
- VM & VBOX (1)
- Tomcat (1)
- Cache (3)
- Others (36)
- design (1)
- PHP (1)
- Try.js (1)
- HTML5 && CSS3 && ECMAScript5 (26)
- 疯言疯语 (5)
- mongodb (2)
- Hardware Common Sence (1)
- RESTful (3)
- Nginx (2)
- web安全 (8)
- Page Design (1)
- web performance (1)
- nodejs (4)
- python (1)
最新评论
-
New_Mao_Er:
求最新的版本破解啊!!!
Omondo eclipseUML插件破解 -
konglx:
讲得仔细,谢了
全面分析 Spring 的编程式事务管理及声明式事务管理 -
cilendeng:
对所有post有效只能使用过滤器
说说Tomcat的Server.xml的URIEncoding=‘UTF-8’配置 -
jiulingchen:
mark了,灰常感谢!
JAVA中最方便的Unicode转换方法 -
anlaetion:
这算法可以有
js 字符串搜索算法
Event delegation in JavaScript
Posted at June 30, 2009 09:00 am by Nicholas C. Zakas
Tags: Delegation , DOM , Events , JavaScript , Performance
Last week, I spoke at and attended the Velocity web performance conference in San Jose. It was a lot of fun and I learned a lot in the other sessions I sat in on. During one session, Steve Souders announced to everyone that I had covered event delegation in my chapter from his new book, Even Faster Web Sites . Unfortunately, Steve misspoke as that topic isn’t covered, so I’m going to fill in the gap with this post.
Traditional event handling
Event delegation is, quite simply, using a single event handler to manage a particular type of event for the entire page. This isn’t a new idea, but it is an important one to grasp for performance. Most of the time, you’ll see code like this in web applications:
document.getElementById("help-btn").onclick = function(event){ openHelp(); }; document.getElementById("save-btn").onclick = function(event){ saveDocument(); }; document.getElementById("undo-btn").onclick = function(event){ undoChanges(); };
This traditional way of coding assigns an event handler to each element that is actionable. For web sites with only a small amount of interaction, this may be okay. Large web applications, however, can grind to a halt when there are too many event handlers. The problem here isn’t necessarily a speed issue but rather a memory issue. If there are hundreds of possible interactions, there will end up being hundreds of ties between DOM elements and your JavaScript code. The more memory required of your web application, the slower it will run in general. Event delegation helps by minimizing this issue.
Event bubbling and capturing
Event delegation would be possible if not for the flowing nature of
events. Early on in web development, browser vendors had to answer a
philosophical question: when you click an area on a web page, what
element are you actually interacting with? The problem came with the
definition of interaction. Clicking within the bounds of an element is
somewhat ambiguous. After all, a click on any element is also within the
bounds of other elements. Consider clicking on a button. You’re
actually clicking within the bounds of the button element, within the
bounds of the <body>
element, and within the bounds of the <html>
element (see figure below).
At the time of this problem, there were two dominant browsers:
Netscape Navigator and Internet Explorer. Each decided to solve this
problem in a different way. Netscape defined an approach called event
capturing, where events first occur on the highest object in the DOM
tree (document) and then work down to the deepest element affected by
the event. So in this example, event capturing has the click event first
handled by document
, then the <html>
element, then <body>
, and finally the <button>
element.
Internet Explorer approached the problem in the exact opposite way.
The IE team defined an approach called event bubbling. Event bubbling
said that the deepest element affected by the event should receive the
event first, then its parent should receive the event, and then it’s
parent, etc., until the document
object finally receives the event. Even though the document doesn’t have a distinct visual representation separate from <html>
, it is still deemed to be its parent and thus bubbling continues up the DOM structure. The previous example would then see the <button>
element receiving the event first, then <body>
, <html>
, and finally, document
.
When defining the DOM, the W3C apparently found merit in both
approaches and so the DOM Level 2 Events specification defines both
event capturing and event bubbling as being present. First, the document
receives the event, then the capturing phase commences to the most
specific element affected by the event. Once the event is handled by
that element, it bubbles back up to the document
. The DOM addEventListener()
method accepts three arguments: the name of the event to handle, a function to execute as the handler, and a Boolean set to true
to handle the event during the capturing phase or false
to handle during the bubbling phase. Most web developers have always been told to provide false
as this argument so that it behaves the same way as attachEvent()
in IE. Example:
//bubbling phase handler document.addEventListener("click", handleClick, false); //capturing phase handler document.addEventListener("click", handleClick, true);
Attaching an event handler via a property (element.onclick = function(){}
),
automatically assumes you want to use the bubbling phase to handle the
event (this is done for backwards compatibility). Pretty much every
browser except Internet Explorer (even through version 8.0) supports the
DOM Level 2 events specification and therefore supports both capturing
and bubbling. Internet Explorer still has its own proprietary event
system that supports just bubbling.
Event delegation using bubbling
The key to event delegation is to use the bubbling aspect of events to handle them at the highest level (usually document
).
Not all events bubble, but mouse and keyboard events do, and
fortunately, those are the ones you’re in which you’re interested.
Revisiting the earlier example, you can handle all of the click
events by assigning an event handler to the document
and then checking the event’s target to determine the course of action.
document.onclick = function(event){ //IE doesn't pass in the event object event = event || window.event; //IE uses srcElement as the target var target = event.target || event.srcElement; switch(target.id){ case "help-btn": openHelp(); break; case "save-btn": saveDocument(); break; case "undo-btn": undoChanges(); break; //others? } };
Using event delegation, the number of functions necessary to manage
events has been cut back to one. All click events are now handled by a
single function which then delegates
to the appropriate function depending on the target of the event. The same can be down for mousedown
, mouseup
, mousemove
, mouseover
, mouseout
, dblclick
, keyup
, keydown
, and keypress
. A word of caution, though, mouseover
and mouseout
are difficult to handle via event delegation due to their nature (the
mouse is considered “out” when it moves from a container to its child).
Note: You can also accomplish event delegation via event capturing, but it only works in browsers that support capturing and therefore not in Internet Explorer.
Benefits
Event delegation has several benefits to the performance of a web application:
- Fewer functions to manage.
- Takes up less memory.
- Fewer ties between your code and the DOM.
- Don’t need to worry about removing event handlers when changing the DOM via
innerHTML
.
Moving from traditional event handling to event delegation has improved the overall performance of large-scale web applications around the world. It’s become so important that JavaScript libraries such as YUI and jQuery have started to bake it into their core interfaces. It really takes very little effort to implement event delegation, but the performance gains can be quite noticeable through the user interface. This is especially apparent when you move from dozens of event handlers to just one. Give event delegation a try and you may just never do traditional event handling again.
[转自 :http://www.nczonline.net/blog/2009/06/30/event-delegation-in-javascript/ ]
发表评论
-
循环数组的逻辑怎么写
2015-03-23 10:24 615应用场景这样的: var imgUrls = [ ... -
发布`代码生成器`
2014-11-17 00:45 555闲话不说,直接上地址 npm: https://www. ... -
MutationObserver
2014-10-27 15:29 1062MutationObserver MutationObse ... -
a simple mvvm library - bird
2014-10-09 18:26 697see here:https://github.com/i ... -
遍历dom tree是一件相当耗时的事情
2014-09-23 01:15 702遍历dom tree是一件相当耗时的事情,尤其是在遍历的同时 ... -
今天再讲下js里的继承
2014-09-18 00:27 660js的继承说简单也很简单,请看: function ... -
Text 类型
2014-09-05 18:52 804文本节点由Text类型表 ... -
JavaScript插入动态脚本
2014-09-05 18:47 604动态脚本指的是在页面加载时不存在,但将来的某一时刻通过修改该 ... -
innerHTML插入<style>元素
2014-09-05 18:37 1106通过innerHTML写入<style>元素没 ... -
CSS实现相对浏览器窗口定位彻底研究
2014-09-05 18:33 3661Web Developer / Designer 经常需要将 ... -
JavaScript插入动态样式
2014-09-05 18:07 570能够把CSS样式包含到HTML页面中的元素有两个。其中,& ... -
再理解jQuery;delete原型属性
2014-05-13 22:05 1818以前用jQuery的时候曾粗略看了它的源码,但却不求甚解。 ... -
javascript &&和||
2012-07-23 00:38 678一直以为 && 和 || ... -
undefined 和 void 0 的区别
2012-07-20 11:15 679在读backbone源码时看见这么一段代码: if ( ... -
Fiddler - 前端开发值得拥有
2012-07-16 14:41 788最近换了新工作,搬了新家,换了新室友,一切都在重新开始。 ... -
说说我的web前端之路,分享些前端的好书
2012-07-16 14:38 761WEB前端研发工程师,在国内算是一个朝阳职业,这个领域没 ... -
JavaScript实现 页面滚动图片加载
2012-07-16 14:29 645又到了这个月的博客时间了,原计划是打算在这个月做一个的功 ... -
JavaScript 操作 Cookie
2012-07-16 11:18 649从事web开发也有些日 ... -
Javascript定义类(class)的三种方法
2012-07-12 12:35 561程序员们做了很多探索,研究如何用Javascript模拟”类” ... -
服务端解决跨源共享
2012-06-21 10:18 4490跨源资源共享是web开发领域中一个非常有趣的话题,互联网 ...
相关推荐
前端项目-gator,Event delegation in javascript
JavaScript_面試_事件傳遞機制和事件委託_Event_Propagation_&_Event_Delegation_-
Understand the important concepts of OOP in JavaScript, such as scope, objects, inheritance, event delegation, and more Find out how the module design pattern is used in OOP in JavaScript Design and ...
This book is for anyone with a foundation in JavaScript who wants to build web applications. Flight is quick and easy to learn, built on technologies you already understand such as the DOM, events, ...
在javasript中,代理、委托经常出现。 那么它究竟在什么样的情况下使用?它的原理又是什么? 这里介绍一下javascript delegate的用法和原理...这个例子主要取自David Walsh的相关文章(How JavaScript Event Delegation
如今的JavaScript技术界里最火热的一项技术应该是‘事件委托(event delegation)’了。使用事件委托技术能让你避免对特定的每个节点添加事件监听器;相反,事件监听器是被添加到它们的父元素上。事件监听器会分析从子...
在需要为较多的元素绑定事件时应该使用事件委托 event delegation javascript事件传播 html如下: <body> <tr><td id=targetTd></td><td></td><td></td></tr> <tr><td></td><td></td><td></td></tr> </...
1.我们通过 事件代理(event delegation) 让事件监听更高效, 2.我们利用 函数降频技术(function debouncing) 来限制一段时间内给定方法被调用的次数,请参考:如何防止事件函数的高频触发(中文翻译) 3.我们使用 ...
事件委托(event delegation):把若干个子节点上的相同事件的处理函数绑定到它的父节点上去,在父节点上统一处理从子节点冒泡上来的事件,这种技术就叫做事件委托。 补充一下:事件委托并不局限于父节点与子节点...
var events = require ( 'dom-delegation-stream' ) var values = require ( 'dom-value-stream' ) events ( document . body , 'input' , 'input[type=text]' ) . pipe ( values ( ) ) . pipe ( wherever ( ) ) ...
海市age楼-骨干脚手架图书馆 Mirage可让您从描述所涉及数据的单个JSON结构生成整个... selector: ".item", // optional, will be used in delegation callback: function(e) // will be bound to the click event
E是一个库,它将 eventBus/发射器、DOM 事件管理、委托事件和基于事件的实用程序组合到一个轻量级和高性能的库中。 E适用于所有主流浏览器和 IE11。 默认情况下,它包括在 IE11 中工作所需的任何 polyfill。...