Search code examples
arraysactionscript-3flashextend

AS-3 - How to override array / implement bracket syntax → []?


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


This is so called bracket syntax that I want to use. If I could use that syntax I could use an array internally to add valid objects to it. It's more about the feeling using an array so I can just replace used arrays with objects of my class.

var obj: MyClass = new MyClass();
obj[2] = "test";


An event when a new object is assigned would help me too.

var arr: Array = [];
arr[2] = "test"; // fire event with index and object ?

Solution

  • 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