Kajetan Abt
Kajetan Abt

Reputation: 1545

Flash: Dynamic button click handler

I need a few pointers on how to create multiple buttons programmatically with different event handlers, or rather: differently parametrized event handlers. My real use is a bit more complex, but it comes down to this: I need a button that can delete itself upon getting clicked.

var Buttons:Vector.<Button> = new Vector.<Button>;      
var newButton = new Button;
var int = Buttons.push(newButton);              
newButton.addEventListener(MouseEvent.CLICK, button_clickHandler);


// pseudocode
button_clickHandler(event:MouseEvent):void {
    if (event.button = i) { delete button i}
}

I can't figure out the way to do this in Flash, except doing something silly like checking mouse position during the click event against all buttons, and then figuring out which one was clicked.

Upvotes: 0

Views: 1102

Answers (1)

You could do something else, but similar:

private function buttonClickHandler(event:MouseEvent):void
{
      var button:Button = Button(event.target);
      var i:int = buttons.indexOf(button);
      // now you know the button instance and the index of the button so do whatever you need

      // delete it from the vector:
      buttons.splice(i, 1);
}

You probably should remove it from the stage too though.

Upvotes: 4

Related Questions