web_starter
web_starter

Reputation: 87

AS3, for loop create button inside movieclip and how to call it?

Here is my full code

import fl.controls.*;

var test:MovieClip = new MovieClip();
var btn:Button;

for(var i:int = 1; i<=7; i++){
    btn = new Button();
    btn.name = "btn" + i;
    btn.x = i * 100;
    test.addChild(btn);
    btn.addEventListener(MouseEvent.CLICK, function(evt:MouseEvent) { nothing(i); });
}

addChild(test);

function nothing(bla:int):void {
    trace("You clicked " + bla);
}

Result:

You clicked 8
You clicked 8
You clicked 8...

Is there anyway, such that, I can use for loop to create different name button, and add it to an event listener?

Upvotes: 0

Views: 3031

Answers (3)

PatrickS
PatrickS

Reputation: 9572

var test:MovieClip = new MovieClip();
var btn:Button;

for(var i:int = 1; i<=7; i++){

 btn = new Button();

 btn.name = i.toString();
 btn.x = i * 100;

 test.addChild(btn);
 btn.addEventListener(MouseEvent.CLICK, nothing);

}


function nothing(event:MouseEvent):void {
    //trace("You clicked " + int( event.currentTarget.name ) );
trace("You clicked " + event.currentTarget.name );
 }

Upvotes: 0

Yevgeny Simkin
Yevgeny Simkin

Reputation: 28349

in your example your i is not doing what you think it's doing. You've declared it as a global variable and passing into the function as you're doing is meaningless. In the end your buttons are simply reporting the current value of i (which after the loop is always 8).

I like the other solution offered, but here's a more object oriented solution, which may be of some use depending on what you're doing with your button (or other objects in the future).

public class MyButton extends Button{
   public var myIndex:Number;
}

Now you use MyButton instead of Button and in your loop throw in

btn.myIndex = i;

then attach generic event handler

btn.addEventListener(MouseEvent.CLICK, myHandler);

which would look like this:

function myHandler(evt:MouseEvent){
   trace(evt.target.myIndex);
}

See... the target of the event will always be the object to which you attached the event. It is to that object that you should attach whatever values you wish it to retain. Personally I prefer this approach because then the information is with the object (and can be used by other elements that might need it) rather than in the handler and only in the handler.

Upvotes: 0

jtbandes
jtbandes

Reputation: 118681

Your problem is the function(evt:MouseEvent){} closure (JavaScript info applies to ActionScript too, as they're both ECMAScript). Here's what you can do:

function makeClickListener(i:int) {
    return function(evt:MouseEvent) {
        nothing(i);
    };
}
...
for(...) {
    ...
    btn.addEventListener(MouseEvent.CLICK, makeClickListener(i));
}

Upvotes: 1

Related Questions