JavaScript Event Delegation is Easier than You Think
6992 단어 JavaScript
By Andrew Tetlaw | July 23, 2008 | JavaScript & CSS
If you’re into adding a little JavaScript interactivity to your web pages you may have heard of JavaScript event delegation and thought it was one of those convoluted design patterns only hardcore JavaScript programmers worry about. The truth is, if you already know how to add JavaScript event handlers, it’s a snap to implement.
JavaScript events are the bedrock of all interactivity on web pages (I mean serious interactivity, not those dinky CSS drop-down menus). In traditional event handling you add or remove event handlers from each element as needed. However, event handlers can potentially cause of memory leaks and performance degradation — the more you have, the greater the risk. JavaScript event delegation is a simple technique by which you add a single event handler to a parent element in order to avoid having to add event handlers to multiple child elements.
How does it work?
Event delegation makes use of two often overlooked features of JavaScript events: http://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/ and the event bubbling . When an event is triggered on an element, for example a mouse click on a button, the same event is also triggered on all of that element’s ancestors. This process is known as event bubbling; the event bubbles up from the originating element to the top of the DOM tree. The target element of any event is the originating element, the button in our example, and is stored in a property of the event object. Using event delegation it’s possible to add an event handler to an element, wait for an event to bubble up from a child element and easily determine from which element the event originated.
How will it help me?
Imagine an HTML table with 10 columns and 100 rows in which you want something to happen when the user clicks on a table cell. For example, I once had to make each cell of a table of that size editable when clicked. Adding event handlers to each of the 1000 cells would be a major performance problem and, potentially, a source of browser-crashing memory leaks. Instead, using event delegation, you would add only one event handler to the
table
element, intercept the click
event and determine which cell was clicked. What does it look like in code?
The code is simple; we only need to worry about detecting the target element. Let’s say we have a
table
element with the ID “ report
” and we have added an event handler to the table for the click
event that will call the editCell
function. The editCell
function will need to determine the target element for the event that has bubbled up to the table
. Expecting that we’ll write a few event handler functions that will need this functionality, we’ll place it in a separate function called getEventTarget
: function getEventTarget(e) {
return e.target || e.srcElement;
The variable
e
represents the event object and we need only a sprinkling of cross-browser code to gain access to and return the target element, stored in the srcElement
property in Internet Explorer and the target
property in other browsers. Next is the
editCell
function that calls the getEventTarget
function. Once we have a reference to the target element it’s up to us to make sure the element is the one we’re expecting: function editCell(e) {
if(target.tagName.toLowerCase() === 'td') {
}
In the
editCell
function we confirm that the target element is a table cell by checking its tag name. That check may be over simplified; what if it’s another element inside the table cell that is the target of the event? A quick modification that adds code to find the parent td
element may be needed. What if some cells should not be editable? In that case we can add a specific class name to a non-editable cell and check that the target element does not have that class name value before making it editable. Many options are available and you’ll just need to choose the one that suits your application. What are the pros and cons?
The benefits of JavaScript event delegation are:
The potential problems may be less clear, but once you are aware of them they’re easily avoided:
blur
, focus
, load
and unload
events don’t bubble like other events. The blur
and focus
events can actually be accessed using the capturing phase (in browsers other than IE) instead of the bubbling phase but that’s a story for another day. mousemove
event you are in serious risk of creating a performance bottleneck because the mousemove
event is triggered so often. The mouseout
event has a target element that is difficult to manage with event delegation. Summary
There are JavaScript event delegation examples available that use major libraries: quirky behaviour , jQuery , and Prototype . You can also find examples using no library at all, like this one from the Yahoo! UI .
Event delegation is a handy tool to have in your kit should the need arise and easy to implement.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
기초 정리 - 1문자 (String) 숫자 (Number) 불린 (Boolean) null undefined 심볼 (Symbol) 큰정수 (BigInt) 따옴표로 묶어 있어야 함 Not-A-Number - 숫자 데이터 / 숫자로 표...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.