!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Lecture 15: Event-based Programming
Lecture 15
Event-Based Programming
Ketan Mayer-Patel
University of North Carolina
Overview
- Events associated with elements of the document.
- Clicks
- Mouse entry/exit
- Mouse movements
- Event handlers are functions designated to deal with an event.
- Called when event occurs
- First parameter is "event object"
- Provides additional information about the event.
- Asynchronous Programming
Another reason why Microsoft is Evil
- W3C Event Model standardizes:
- Event names
- Event propagation
- Event binding
- Event data
- Microsoft does all of this slightly differently
- Prototype to the rescue
Observe
- observe(event_name, handler)
- Method of element objects
- event_name
- String name of event to observe
- handler
- Function object that will handle the event
- Need to wait until DOM is loaded before setting up handlers
Event Names
- Mouse Events
- click, mousedown, mouseup, mouseover, mousemove, mouseout
- Keyboard Events
- Form Events
- Prototype Custom Events
Example 1
- Setting style dynamically
- setStyle()
- getStyle(style_attribute)
- Retrieves style value (not used in the example).
- Using the same function as handler for more than one element
- The this keyword is set to the specific element where handler is registered.
- Using prompt() to get input from the user
Event Data
- Additional information about the event provided in first parameter to event handler.
- Sometimes referred to as the 'event data object'.
- Specific properties available depending on what kind of event occured
- Mouse events
- pointerX(), pointerY()
- isLeftClick(), isMiddleClick(), isRightClick()
Example 2 Problems
- Text selection mixed in with dragging.
- Go too fast and we lose control.
Stopping Default Behavior
- Browser has a default behavior along with any handlers
- Text selection when dragging on text.
- Form submission generating HTTP request.
- Following links when clicked.
- To stop default behavior:
- Call preventDefault() method on event data object.
Example 3
- Example 2 text selection problem fixed.
Event Propagation
- Event is delivered first to element where it occurs.
- Event propagated up the DOM tree.
- Any/all handlers registered for that event called in turn as it goes up.
- this set to each element as appropriate
- Event data object always has reference to original element where event occurred
- element() method of event data object.
- Stopping propagation
- stopPropagation() method on event data object
Example 4
- Event propagation demonstrated.
Fixing Drag/Drop
- How can we use event propagation to fix drag/drop.
- Problem: As we are dragging, if we go too fast, we lose the events since they are no longer occuring on the element being dragged.
Example 5