2007年8月12日星期日

Proxy: getProperty and setProperty

getProperty and setProperty are methods used in Proxy classes that are used to manage property access. When a property not defined within a proxy instance is retrieved, getProperty is called to retrieve it. When set, setProperty is used to set it.

As with all methods of the Proxy class, getProperty and setProperty are defined within the flash_proxy namespace (flash.utils.flash_proxy) to prevent conflicts with public. When you override these methods within your own Proxy subclasses, you will want to be sure to use the flash_proxy namespace.

The following example, CustomObject, extends Proxy and uses getProperty and setProperty to manage dynamic properties set for its instances.

ActionScript Code:

package {

import flash.utils.Proxy;
import flash.utils.flash_proxy;

dynamic public class CustomObject extends Proxy {

public var classProperty:String = "classProperty"; // generic class variable
private var customProperties:Object = new Object(); // store custom variables

public function CustomObject() {
}

// called when getting dynamic variables
override flash_proxy function
getProperty(name:*):* {
if (name in customProperties) {
return customProperties[name];
}
return "Property does not exist";
}
// called when setting dynamic variables
override flash_proxy function
setProperty(name:*, value:*):void {
customProperties[
name] = "Property "+name+": "+value;
}
}
}

ActionScript Code:

// usage example
var myObj:CustomObject = new CustomObject();
trace(myObj.foo); // Property does not exist
myObj.
foo = "bar";
trace(myObj.foo); // Property foo: bar

trace(myObj.classProperty); // classProperty
myObj.
classProperty = "bar";
trace(myObj.classProperty); // bar


Notice that when getting and setting the foo property, getProperty and setProperty are used to control its ultimate value which is stored within a customProperties defined for the class. Also, since classProperty is not a dynamic variables, instead being one defined for the class, getProperty and setProperty to not apply.

0 评论: