AS3,向构造函数类添加事件监听器?

时间:2013-11-13 10:44:41

标签: actionscript-3 flash class

这可能很简单,我不能为我的生活找出原因,为什么这不起作用。我正在尝试创建一个对象(仅用于测试)并在构造函数中分配事件侦听器。在我脑海里,它应该工作,但我相信我一定会遗漏一些东西:

package  {

import flash.display.MovieClip;
import flash.events.MouseEvent; 

public class Box extends MovieClip {

    public function Box() {
        // constructor code
        var mySound:Sound = new Bark();
        trace("Box created");
        height=800;
        width=300;
        x=100;
        y=100;
        addEventListener(MouseEvent.MOUSE_OVER, overThis);
        addEventListener(MouseEvent.CLICK, clickToPlay);
    }

    public function overThis(m:MouseEvent){
        trace("SADF");          
    }

    function clickToPlay(m:MouseEvent){
        mySound.play();
    }

}}

通过这样做,我希望“盒子”在管理自己的事件方面是自给自足的。 (请忽略play()之类的东西,当我直接在MAINDOC.as中运行时,这一切都有效。

这是主要的文件:

package {
import flash.display.MovieClip;
import flash.media.Sound;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.ColorTransform;

public class MainDoc extends MovieClip
{
    public function MainDoc()
    {
        // constructor code
        init();

        function init()
        {
            createBox(300,300);
        }

        function createBox(newX,newY)
        {
            var box = new Box();
            box.x = newX;
            box.y = newY;
            addChild(box);
        }

    }
}}

当我测试它时会创建框(我已绘制)但不运行任何事件?

希望你们能帮忙

1 个答案:

答案 0 :(得分:2)

您必须在盒子中添加一些图形,以便MouseEvents可以工作:

public function Box() 
{
    // constructor code
    var mySound:Sound = new Bark();
    trace("Box created");

    // begin the filling of some graphics, you can change color/alpha as you want
    this.graphics.beginFill( 0x000000, 1 );
    // make a rectangle 300x800
    this.graphics.drawRect(0,0,300,800);
    // stop filling
    this.graphics.endFill();


    // you don't need it anymore
    //height=800;
    // you don't need it anymore
    //width=300;

    // place your clip where you want but you do that in the Main class so no need there
    //x=100;
    //y=100;

    // now you have graphics attached to your MovieClip the MouseEvent must work
    addEventListener(MouseEvent.MOUSE_OVER, overThis);
    addEventListener(MouseEvent.CLICK, clickToPlay);
}

希望能帮助你:)