Section 5.2. Mozilla Get and Set Methods


5.2. Mozilla Get and Set Methods

In anticipation of future ECMA adoption of a new language feature, Mozilla-based browsers provide a mechanism for defining functions that perform the acts of reading (getting) and writing (setting) custom properties of objects, and attaching those functions 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 statementshandled 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. The W3C DOM doesn't 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_ _( ) method is 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.




Dynamic HTML. The Definitive Reference
Dynamic HTML: The Definitive Reference
ISBN: 0596527403
EAN: 2147483647
Year: 2004
Pages: 120
Authors: Danny Goodman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net