难以将事件附加到以编程方式创建的MovieClip

时间:2011-11-17 07:34:15

标签: events actionscript dynamic constructor

这一直是我的烦恼,我在搜索解决方案时似乎无法提出正确的问题!问题很简单:为什么我不能将事件附加到Actionscript 3中以编程方式创建的MovieClip?这必须是我缺少的基本东西,对吧?

package {

    //imports
    import flash.display.*;
    import flash.events.*;

    //document class
    public class Document extends MovieClip {

        //variables
        public var utilities:Object;
        public var test:MovieClip;

        //constructor
        public function Document()
        {

            //instantiate the utilities object - this will contain some
            //simple functions for setting dimensions and background color of
            //a display object.
            this.utilities = new Object();

            //utility function: set dimensions.
            this.utilities.setDimensions = function(what:*, width:uint, height:uint)
            {
                what.graphics.drawRect(0, 0, width, height);
            }

            //utility function: set opaque background color. 
            this.utilities.setBgColor = function(what:DisplayObject, color:uint)
            {
                what.cacheAsBitmap = true; 
                what.opaqueBackground = color;
            }

            //create/add a test movie clip.
            test = new MovieClip();

            //set dimensions and background color of the test movie clip.
            this.utilities.setDimensions(test, 100, 100);
            this.utilities.setBgColor(test, 0xff0000);

            //add test movie clip to document class.
            this.addChild(test);

            //add a click event to the test movie clip.
            test.addEventListener(MouseEvent.CLICK, onClick);

        }

        //click event handler
        private function onClick(evt:Event):void
        {
            trace('click');
        }   
    }
}

//update based on Casey Yee's answer
//the set dimension function needs to contain a fill to be clickable
//a fill is added with alpha set to zero to maintain transparency.

//utility function: set dimensions 
this.utilities.setDimensions = function(what:*, width:uint, height:uint)
{
    what.graphics.beginFill(0x000000, 0);
    what.graphics.drawRect(0, 0, width, height);
    what.graphics.endFill();
}

1 个答案:

答案 0 :(得分:2)

测试仍然是一个空的影片剪辑,尝试在其中添加绘图:

test = new MovieClip();
test.graphics.beginFill(0xFF0000);
test.graphics.drawRect(0,0,100,100);
test.graphics.endFill();