start page | rating of books | rating of authors | reviews | copyrights

Dynamic HTML: The Definitive Reference, 2rd Ed.Dynamic HTML: The Definitive ReferenceSearch this book

12.3. Mozilla Get and Set Methods

In anticipation of future ECMA adoption of a new language feature, Mozilla-based browsers (e.g., Netscape 6 and 7) provide a mechanism for defining functions that perform the acts of reading (getting) and writing (setting) custom properties of objects, and attaching those function to objects. To prevent collision with the eventual standardized syntax, the Mozilla version utilizes a special double-double underscore syntax (i.e., two underscore characters on each side of the method name) for two methods of any object's prototype property:

objectName.prototype._ _defineGetter_  _("propertyName", functionReference);
objectName.prototype._ _defineSetter_  _("propertyName", functionReference);

The reason this mechanism is different from simply assigning a custom prototype property is that the actions required to get or set a property value may require multiple script statements—handled by the function referenced in the prototype methods.

To demonstrate this facility, the following examples operate on a DOM object (but any object you can reference with JavaScript will do) to provide an innerText property for all HTML element objects. Neither the W3C DOM nor Netscape 6 offer this property, but you can add it to all elements in the page by having these method statements in the page's scripts. The functions defined here are anonymous functions (for compactness), but any function reference will suffice. In a cross-browser application, these statements would have to be protected so that they run only when the HTMLElement is referenceable and the _ _defineGetter_ _( ) or _ _defineSetter_ _( ) methods are implemented (all verifiable through object detection):

HTMLElement.prototype._ _defineGetter_  _("innerText", function ( ) {
    var rng = document.createRange( );
    rng.selectNode(this);
    return rng.toString( );
});
HTMLElement.prototype._ _defineSetter_  _("innerText", function(newTxt) {
    var rng = document.createRange( );
    rng.selectNodeContents(this);
    rng.deleteContents( );
    this.appendChild(document.createTextNode(newTxt));
    return newTxt;
});

Whenever a script statement attempts to read the innerText property of an element, the function associated with the _ _defineGetter_ _( ) method is executed, returning the desired value. Conversely, whenever a value is assigned to the innerText property of an element, the _ _defineSetter_ _( ) method's function runs.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.