Thursday, February 10, 2011

Event Handling For Toolbar Using Haxe Targeting Flash

I am creating a simple UI toolbar component in Haxe for use in a Flash game. The toolbar is your general UI style toolbar, it has a background and several buttons. When the buttons are clicked some game action happens.

I have a question about the best way to implement events for the toolbars buttons. A parent class will create a toolbar and then sign up any functions it wants to the button on click events.

My current solution looks like this:

  • The toolbar extends the sprite class.
  • The toolbar class has a child sprite for each button.
  • Each button has an event listener for MouseEvent.Click event.
  • The MouseEvent.Click is handled by a function on the toolbar that examines a Dynamic typed array and executes each function contained in the array.
  • The Dynamic typed array is public so any classes that want to sign up to the toolbar button on click events can add their callback function to the array.

Code Snippet for a Scene that has a toolbar

this.toolbar = new ToolBar();
this.toolbar.OnAttackButtonClicked.push(OnAttackButtonClicked);

Code Snippet for creating a button in the toolbar

this.attackButton = new Sprite();
this.attackButton.addEventListener(MouseEvent.CLICK, this.OnAttackButtonClickListener);

Code Snippet for the button click handler in the toolbar

private function OnAttackButtonClickListener(event : MouseEvent) : Void
{
    if (this.OnAttackButtonCallbacks != null)
    {
     var index:Int = this.OnAttackButtonCallbacks.length;
     while (index-- > 0) 
     {
      this.OnAttackButtonCallbacks[index](event);
     }
    }
}

I am wondering if this is a good approach or if there is a better way to do it?

  • Solved. Used Custom Events and the Event Dispatcher.

0 comments:

Post a Comment