Oleg Tarasenko
Oleg Tarasenko

Reputation: 9610

AS3: How to dispatch event from actionscript class

I have small chess application which consists of cells and boards. When user moves an item to the board, I want the board cell to dispatch an event so Board can listen to it and call a listener

public class BoardCell extends Canvas
{
  public function Sample():void
  {
      ....Some code
      var e:Event = new Event("newMove")
  dispatchEvent(e);
  }
 }

However, I can't catch the event in parent chess board class (Not sure that I listen for it correctly)

    public class FrontEndBoard extends ChessBoard
{

    private var initialPoition:String;

    public function FrontEndBoard()
    {
        //TODO: implement function
        this.addEventListener(Event.ADDED_TO_STAGE, addedToStage);
        this.addEventListener("newMove", moveEvent);
        super();
    }

Upvotes: 6

Views: 12155

Answers (3)

chrissr
chrissr

Reputation: 9921

I'm not sure how exactly FrontEndBoard and BoardCell are hierarchically in your application, but you may need to tell the "newMove" event that it can bubble.

var e:Event = new Event("newMove", true);

Upvotes: 4

Christophe Herreman
Christophe Herreman

Reputation: 16085

The event you dispatch from the BoardCell class should bubble, so it is caught in any parent classes. Check the constructor arguments of the Event class where you can set the "bubbles" flag to true.

Upvotes: 1

Eran
Eran

Reputation: 1702

you have 2 options :

1) instead of this.addEventListener("newMove", moveEvent); do BoardCell.addEventListener("newMove", moveEvent);

2) have the event buble up to the parent ( assuming BoardCell is a display child of FrontEndBoard , you set it as a parameter in the event constructor )

var e:Event = new Event("newMove",true) .

Upvotes: 5

Related Questions