n4pgamer
n4pgamer

Reputation: 624

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:

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 ?

Upvotes: 1

Views: 339

Answers (3)

Pan
Pan

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

catholicon
catholicon

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

Fygo
Fygo

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

Related Questions