8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

as3signals で ActionScript3 の Event をやめよう

Last updated at Posted at 2014-02-27

Event な書き方

AS3 で自作の Event を使うとき、だいたいこんな感じになる。

ButtonEvent.as
public class ButtonEvent extends Event
{
    public static const CLICKED:String = 'CLICKED';
    public function ButtonEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
    {
        super(type, bubbles, cancelable);
    }
}
Foo.as
public class Button extends EventDispatcher
{
    public function click():void
    {
        dispatchEvent(new ButtonEvent(ButtonEvent.CLICKED));
    }
}
Bar.as
var button:Button = new Button();
button.addEventListener(ButtonEvent.CLICKED, function(e:Event):void {
    trace("The button clicked.");
});

as3signals での書き方

Foo.as
public class Button
{
    public const clicked:Signal = new Signal;
    public function click():void
    {
        clicked.dispatch();
    }
}
Bar.as
var button:Button = new Button();
button.clicked.add(function():void {
    trace("The button clicked.");
});

メリット

  • Button クラスがむやみに EventDispatcher を継承しなくて良い
  • 文字列を使ったイベントの識別を行わなくて良い
    • 例えば ButtonEvent.CLICKED と ToggleEvent.CLICKED が同じ "CLICKED" だったりするとバグっても気づきにくい
  • Button が dispatch するイベント(シグナル)がソースコードに明示的に書かれていて、コンパイル時に決定されている
  • 記述量がすくない

ギッハブ→ https://github.com/robertpenner/as3-signals

8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?