Reputation: 624
I'm trying to extend the class Array
. I want to have some kind of notification when objects are added to my array and then do some additional checking/manipulation.
The most interesting part is something like:
array[2] = object;
array.hello = "world";
This is where I'm stuck at:
public dynamic class Array2 extends Array
{
}
var array: Array2 = new Array2();
array[2] = "hello world"; // need to do some verification before adding
var obj: MyClass = new MyClass();
obj[2] = "test";
var arr: Array = [];
arr[2] = "test"; // fire event with index and object ?
Upvotes: 1
Views: 339
Reputation: 2101
You can create your class that extends flash.utils.Proxy
Here is a sample
import flash.utils.Proxy;
import flash.utils.flash_proxy;
public dynamic class MyArray extends Proxy {
private var acturalArray:Array;
public function MyArray() {
super();
acturalArray = [];
}
override flash_proxy function setProperty(name:*, value:*):void {
//do some verification before set value,
if (acturalArray[name] != undefined) {
return;
}
acturalArray[name] = value;
}
override flash_proxy function getProperty(name:*):* {
return acturalArray[name];
}
}
And here is how to use it
var p:MyArray = new MyArray();
p[1] = 5;
p[1] = 2;
var d:int = p[1];//d will be equal to 5
Upvotes: 1
Reputation: 1165
I think what you need is a Proxy class. I was about to write a small piece of code right here, but then saw that the doc page already has some nice examples to show the usage.
Upvotes: 1
Reputation: 4665
Why do you need to subclass it? Is it absolutely necessary to use the [] syntax or make it a dynamic class? You could easily do something like this instead:
public class Test {
private var arr:Array = [];
public function Test() {
}
public function add(o:*):void {
arr.push(o);
//dispatch event
}
}
}
Edit (after seeing yours): Well, in that case you basically need to declare your class dynamic. I am not quite sure how to check in that case that a property was added without some timer/enterframe.
Upvotes: 0