PDA

View Full Version : Reference to class methods



ThinkKirupa
March 16th, 2009, 05:23 AM
Hi there,


I need a way to reference to object (or the class methods inside). I have a button "Add box" and when it is pressed it creates a new instance of class "MyBox". The thing is everyone of these objects get the same name "box".


Here's a hint of what it's like:


var arrBoxes:Array = new Array();
// var n:Number = 1;

function addBox(event:MouseEvent):void
{
var box:MyBox = new MyBox();
// var "box"+n:MyBox = new MyBox();
// n++;

factory.addChild(box);


box.name = "box"+(arrBoxes.length+1)+"_mc"; // box1_mc, box2_mc, box3_mc, ...
arrBoxes.push(box.name);
}


function changeColor(event:MouseEvent):void
{
factory.box1_mc.setColor(red); // changeColor is public function inside of "MyBox" class
// box1.setColor(red);
}

Inside of the addBox function I can easily refer to the Object with just "box" (for example box.name = ..)but when in another function I cannot (and by then I might have created many "box"es).

nook
March 16th, 2009, 05:29 AM
You're halfway there already by putting them into an array. So you just need to think of a way to pick the correct box from that array when you need to (either through its name, its index, or some other id).

Notice that you've used both "box1_mc" and "box1" as a reference.

cheers :: nook

Iamthejuggler
March 16th, 2009, 05:34 AM
That's actually not possible (as far as i know). One way to get around it is to create the instance with it's generic id ("box"), then add it to a Dictionary, with the key as the unique string you want.

ThinkKirupa
March 16th, 2009, 06:32 AM
Hmm...


Notice that you've used both "box1_mc" and "box1" as a reference.

The comment code was just an imaginary solution.


Is it possible to use just arrBoxes.push(box); ?

It seems a bit odd to start the code initiate 50 instances of class MyBox so that they can be used later on.
var box1:MyBox = new MyBox();
var box2:MyBox = new MyBox();
var box3:MyBox = new MyBox();
var box4:MyBox = new MyBox();
.....

There must be a way to create instances of a class (at runtime) and give them a individual reference name so that you then will be able to communicate with each of them?

Dictionary seems a bit advanced.

nook
March 16th, 2009, 10:05 AM
You've already given them unique identification by saying:

box.name = "box"+(arrBoxes.length+1)+"_mc";

To access a box you can write:
var box:MyBox = factory.getChildByName("box"+id+"_mc");