Hamed Kamrava
Hamed Kamrava

Reputation: 12867

Find out Button position in array of objects

I've created a Button symbol and export it Export for ActionScript with class name "theButton".

There is an object and i would like to create that Button in myObj constructor as below :

public class myObj extends Sprite {
        private var myBtn:theButton = new theButton();

        public function myObj() {
            x = Math.floor(Math.random() * 300) + 50;
            y = Math.floor(Math.random() * 300) + 50;
            addChild(myBtn);
        }
        public function getXPos():uint {
            return x;
        }
    }

I'm trying to create an array of myObj class and getXPos() when i do clicking on each button like so :

var myArray:Array = new Array();
myArray[0] = new myObj();

myArray[0].addEventListener(MouseEvent.CLICK, Clicked);

addChild(myArray[0]);

function Clicked(evt:MouseEvent):void {
    var xPos1:uint = myObj(evt.target).getXPos();
    trace("Position is in : " + xPos1);
}

When clicking on the buttons appears on the screen, following error has comes up:

Type Coercion failed: cannot convert theButton@2c9dcf99 to myObj.

Please tell me what am i doing wrong ?

Upvotes: 0

Views: 53

Answers (1)

Strille
Strille

Reputation: 5781

evt.target will contain a reference to the clicked display object, which actually is myBtn inside the myObj class (it's the only visible graphics you can click on).

There are two ways to solve this.

  1. Set this.mouseChildren = false inside the myObj() constructor. This way a click on a child display object in myObj will be "counted" as a click on myObj, and evt.target will be a reference to an instance of myObj.

  2. Instead of evt.target use evt.currentTarget. It's the instance you attached the event listener to, not the instance you clicked on (That is actually what you want in most cases).

Upvotes: 2

Related Questions