如何将EventListener添加到moiveClips / Sprites的scaleX更改事件?

时间:2010-06-05 06:39:38

标签: flex flash actionscript-3 actionscript

如何在Flash AS 3中触发movieClip或Sprite的scaleX属性更改事件。

1 个答案:

答案 0 :(得分:1)

例如:CustomSprite.as

package view {
import flash.display.Sprite;
import flash.events.Event;
import events.ScaleChangeEvent;

public class CustomSprite extends Sprite {

    override public function set scaleX(value:Number):void {
        super.scaleX = value;
        dispatchEvent(new ScaleChangeEvent(ScaleChangeEvent.SCALE_CHANGED));
    }

    public function CustomSprite() {
        super();
    }

    override public function dispatchEvent(event:Event):Boolean {
        if (willTrigger(event.type)) {
            return super.dispatchEvent(event);
        }
        return true;
    }
}}

ScaleChangeEvent.as

package events {
import flash.events.Event;

public class ScaleChangeEvent extends Event {

    public static const SCALE_CHANGED:String = "scaleChanged";

    public function ScaleChangeEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false) {
        super(type, bubbles, cancelable);
    }

    override public function clone():Event {
        return new ScaleChangeEvent(type, bubbles, cancelable);
    }

    override public function toString():String {
        return formatToString("ScaleChangeEvent", type, bubbles, cancelable, eventPhase);
    }
}}

Test.as

package {
import flash.display.Sprite;
import flash.events.Event;
import view.CustomSprite;
import events.ScaleChangeEvent;

public class Test extends Sprite {

    public function Test() {
        addEventListener(Event.ADDED_TO_STAGE, addedToStageListener, false, 0, true);
    }

    private function addedToStageListener(event:Event):void {
        removeEventListener(Event.ADDED_TO_STAGE, addedToStageListener);

        var customSprite:CustomSprite = new CustomSprite();
        customSprite.addEventListener(ScaleChangeEvent.SCALE_CHANGED, scaleChangedListener, false, 0, true);
        customSprite.scaleX = 0.2;
    }

    private function scaleChangedListener(event:ScaleChangeEvent):void {
        trace(event.target.scaleX);
    }
}}