Although event handlers are functions like any other, they are not called from global code and therefore are running in a different scope chain context to that which your functions normally execute.
The head of the scope chain is the call object. Arguments passed to the event handler are available here as they would be in other function calls.
In a normal context, the next object in the scope chain might be the global object. However for the event handler, it is the object to which the event was directed. This makes event handles somewhat easier to write.
For example, the form object yielded in the scope for an event handler attached to an <INPUT> tag is the form object that the FormElement object belongs to. This scope chain continues up the document hierarchy (the DOM), until it reaches the global object. You can share various parts of the form handling code by plugging it into objects at different points in the DOM.
The scope chain for an <INPUT> object is the reverse of its DOM location. Thus:
window.document.form.button.event
will seek to resolve its identifiers in this order:
call object
button object
form object
document object
window (global) object
You need to be explicit about how objects and event handlers are declared and called.
Inside an event handler, you should call window.open() and not just open() because the document object is located sooner in the scope chain than the window object. This means that open() will call the document.open() method before it would have resolved to the window.open() method.
You should also be careful not to add properties to your objects whose name is the same as other pre-defined objects in the DOM. If you do, you risk seriously compromising your script's ability to run correctly within its scope.
Beware that only the code defined in the HTML tag attribute is executed in an event handler scope chain. Calls to other functions will execute them in the scope that they are defined in due to the static scope rules for functions. You can get round this by defining a JavaScript version 1.2 Closure object. However this technique is not supported by MSIE version 4 browsers.
See also: | Document, Element.onevent, Function scope, Function.call() |
Prev | Home | Next |
Event handler properties | Up | Event management |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. |