Skip to main content

JS Learning Notes 6_Events

Free2015-04-11#JS#js事件

This article introduces event flow, event delegation, some common sense and performance optimization strategies

1. Event Bubbling##

Inside-out event propagation (feeling like an arrow flying out from the screen)

2. Event Capturing##

Outside-in event propagation (feeling like force penetrating through paper)

3. DOM Event Flow (DOM Level 2)##

Event capturing phase -> At target phase -> Event bubbling phase (feeling like sticking a needle through the screen from the screen, sewing clothes)

Event capturing is event propagation from DOM tree root to leaves, so can capture (event.stopPropagation) events at positions close to the root, letting leaves not receive event signals

Event bubbling is the return process from leaves to root along the original path, so can centrally handle (event.target) leaf events at positions close to the root, which is the so-called event delegation. Centralized handling can avoid binding event handlers to multiple leaves, reducing response speed

At target phase is just specification requirement, browsers don't really support it

Note: [IE9+] supports event capturing, event bubbling is supported by all browsers

4. Several Ways to Add Event Handlers##

  1. HTML: onEventName = strCode. Properties that event handler function can directly access = global properties + properties of form where element is located + element's own properties

Automatic scope expansion method is equivalent to:

    function(){
      with(document){//global properties
        with(this.form){//form properties
          with(this){
            //own properties
          }
        }
      }
    }
    

Event handler function can directly access so many properties, so can do like this:

    <form method="post">
      <input type="text" name="user_name" value="">
      <input type="button" value="Get Username" onclick="alert(user_name.value)">
    </form>
    

2. DOM Level 0: elem.onEventName = functionName/null;

Event handlers added this way execute during bubbling phase, directly accessible properties = global properties + element's own properties

  1. DOM Level 2: (supported by modern browsers) elem.add/removeEventListener(eventName, functionName, false/true);

false means adding during event bubbling phase, true means adding during event capturing phase. Directly accessible properties same as above

  1. [IE8-]: elem.attach/detachEvent(onEventName (on cannot be omitted), functionName);

Directly accessible properties only global properties, and among multiple handlers added for the same event, the last added executes first, opposite to DOM Level 2 standard

P.S. [IE8-] only supports event bubbling, so no third parameter, defaults (and can only be) adding during event bubbling phase

5. What's the Use of Event Object?##

btn.onclick = function(event){
  //event.target; get event source
  //event.preventDefault(); cancel default behavior, such as link navigation behavior
  //event.stopPropagation(); block event propagation
  //and some less commonly used ones
}

Note: Above code is not fully browser compatible, event object properties are also incomplete, for more information please see [JS Native Event Handling (Cross-browser)](/articles/js 原生事件处理(跨浏览器)/)

6. Event Classification##

  1. UI Events

  2. Focus Events

  3. Mouse Events

  4. Wheel Events

  5. Text Events

  6. Keyboard Events

  7. Composition Events (input with IME)

  8. Mutation Events (DOM structure updates)

  9. HTML5 Events

  10. Device Events (specific devices, such as game consoles)

  11. Touch and Gesture Events

7. Event Delegation##

Use event bubbling to reduce event handlers, to improve performance. Can even add event handlers to document object, for shorter interaction preparation time (takes time to establish connection between page elements and event handlers)

Advantages of Event Delegation:

  1. Less time needed to set event handlers, because DOM access count is reduced

  2. Less memory space occupied, because event handlers are reduced

  3. Shorter interaction preparation time, because connections needed to be established between page elements and event handlers are reduced

  4. Faster page response speed, because connections established between page elements and event handlers are reduced

8. Notes on Removing Event Handlers##

Before target element is removed from DOM tree, should manually remove event handlers bound to it, to avoid invalid event handlers occupying memory

Before page unload, best to manually remove all event handlers in page, because [IE8-] when unloading page, event handlers will stay in memory. Can remove in unload event handler

The essence of removing event handlers is disconnecting the connection between page elements and event handlers

9. Ways to Simulate Events (i.e., Code Triggers Specified Events)##

  1. Create event object

  2. Initialize various properties of event object

  3. Trigger event

Note: [IE8-] implementation differs from DOM specification; only DOM Level 3 can perfectly simulate keyboard events

10. Common Sense and Performance Optimization Strategies##

  1. Only add event handlers at capturing phase when needing to intercept other events, because [IE8-] doesn't support event capturing

  2. For dynamically created img elements, as soon as src attribute is set, related content starts downloading, not after new element is inserted into DOM tree

  3. For dynamically created script elements, only starts downloading after inserting into DOM tree

  4. For dynamically created link elements (used to load external styles), only inserting into head section can guarantee consistent browser behavior, and external styles default to asynchronous loading

  5. Use in operator to detect event support, for example:

    if('onload' in elem){
      //do sth
    }
    
  6. What's the difference between hover, mouseover, mouseout, mouseenter, mouseleave?

    • hover is CSS pseudo-class, triggers when mouse enters and is within target element;
    • mouseover is mouse event, triggers when mouse enters target element, has widespread browser support. Equivalent to mouseenter, but mouseenter doesn't have full support;
    • mouseout is opposite of mouseover, mouseleave is opposite of mouseenter, latter doesn't have full support;
    • Local test: FF and IE fully support, Chrome doesn't support enter/leave.
  7. Event delegation is the most important optimization strategy, of course, delegation is not perfect, delegation causes logic entanglement, for example in extreme case, adding one event handler to document object is enough, but that will be a very large function... So, should use delegation as much as possible at appropriate places

  8. Removing expired event handlers in time can reduce memory usage, this is space optimization strategy

Comments

No comments yet. Be the first to share your thoughts.

Leave a comment