Except where otherwise noted, the contents of this presentation are Copyright 2009 Marty Stepp and Jessica Miller.
9.2: Event-Handling
9.1: The Prototype JavaScript Library
9.2: Event-Handling
The keyword this(8.1.3)
this.fieldName// access field
this.fieldName = value; // modify field
this.methodName(parameters); // call method
all JavaScript code actually runs inside of an object
by default, code runs inside the global window object
all global variables and functions you declare become part of window
the this keyword refers to the current object
Event handler binding
function pageLoad() {
$("ok").onclick = okayClick;// bound to okButton here
}
function okayClick() { // okayClick knows what DOM objectthis.innerHTML = "booyah"; // it was called on
}
window.onload = pageLoad;
event handlers attached unobtrusively are bound to the element
inside the handler, that element becomes this (rather than the window)
function processDucks() {
if ($("huey").checked) {
alert("Huey is checked!");
} else if ($("dewey").checked) {
alert("Dewey is checked!");
} else {
alert("Louie is checked!");
}alert(this.value + " is checked!");
}
if the same function is assigned to multiple elements, each gets its own bound copy
// listen to clicks on all buttons with class "control" that
// are directly inside the section with ID "game"
window.onload = function() {
var gameButtons = $$("#game > button.control");
for (var i = 0; i < gameButtons.length; i++) {
gameButtons[i].observe("click", gameButtonClick);
}
};
function gameButtonClick() { ... }
you can use $$ and other DOM walking methods to unobtrusively attach event handlers to a group of related elements in your window.onload code
The Event object
function name(event) {
// an event handler function ...
}
Event handlers can accept an optional parameter to represent the event that is occurring. Event objects have the following properties / methods:
method / property name
description
type
what kind of event, such as "click" or "mousedown"