!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Lecture 16
Event-Based Programming, part 2
Ketan Mayer-Patel
University of North Carolina, Chapel Hill
Dynamically adding/stopping event handlers
- Often you will want to dynamically add/stop event handlers dynamically.
- In other words, as the result of some prior event, you may want to start handling an event...
- ... and then stop handling the event in the future when something else occurs.
- To stop observing an event use:
stopObserving(event, handler)
- event: Name of event to stop observing as a string.
- handler: Function object that we had previously registered with observe()
Example 1
- In our revised version of the drag/drop, we do this to:
- Start observing mouse move events only when a drag has started.
- Stop observing mouse move events when the drag is over.
- See Example 1
Stop Propagation
- Example 2
- Tree-view of nested items.
- stopPropagation() needed to prevent parent items from collapsing when we click on child items.
Keyboard Events
- Elements need to be able to get the keyboard focus in order to handle keyboard events.
- Some elements like form inputs are enabled by default.
- To enable focus on others, set tabindex attribute.
- Numeric value that determines relative tabbing order.
- Getting the keyboard focus results in a 'focus' event.
keyCode and charCode
- Properties of event data object that indicate which key was pressed.
- keyCode for non-character keys
- charCode for character keys
- String.fromCharCode() can be used to conver charCode to a string
- Prototype defines useful constants for many keyCodes as properties of Event:
- Event.KEY_UP, Event.KEY_DOWN, Event.KEY_LEFT, Event.KEY_RIGHT
- Example 3