在AS3中添加/删除子视频剪辑中的事件侦听器

时间:2013-04-05 19:18:58

标签: actionscript-3 flash flash-cs5

简而言之,这就是我想要完成的事情:

  1. 点击影片剪辑,添加儿童
  2. 点击儿童影片剪辑,播放声音
  3. 再次点击子项,停止声音
  4. 第三次点击儿童,删除儿童
  5. 可悲的是,我只是走到了第1步。我已经想出了如何在点击父级影片剪辑时播放声音(我正在使用连接),但是当我尝试完之后和孩子一起,我收到以下错误:

    TypeError:错误#1010:术语未定义且没有属性。(我不再收到此错误)

    场景1,图层'动作',第1帧,第29行1120:访问未定义属性newBox。

    
        leftBox.addEventListener(MouseEvent.CLICK, addBox);
        function addBox(event:MouseEvent):void 
    
        {
        var newBox:right_box = new right_box();
        addChild(newBox);
        newBox.x = 0;
        newBox.y = 0;
        newBox.width = leftBox.width;
        newBox.height = leftBox.height /2;
    
        }
        newBox.addEventListener(MouseEvent.CLICK, playSound);
        function playSound(event:Event)
        {
        var mySound:testSound = new testSound();
        mySound.play();
    
        }
    
    

    非常感谢任何帮助。

    谢谢!

    (P.S。我是n00b,所以请你好!)

1 个答案:

答案 0 :(得分:0)

您尝试在创建新事件之前向其添加事件侦听器。请按以下步骤操作:

// mySound should be availible in scope
var mySound:testSound = new testSound();

// newBox also
var newBox:right_box;
// here is a channel for you
var channel: SoundChannel;

// ok this adds the first listener...
leftBox.addEventListener(MouseEvent.CLICK, addBox);


function addBox(event:MouseEvent):void {
    newBox = new right_box();
    addChild(newBox);
    newBox.x = 0;
    newBox.y = 0;
    newBox.width = leftBox.width;
    newBox.height = leftBox.height /2;
    // you should add listener here...
    newBox.addEventListener(MouseEvent.CLICK, playSound);
    // you have to avoid multiple newBoxes on each other and
    // leaving the older ones under..
    // So stop listening to the newBox generating event: 
    leftBox.removeEventListener(MouseEvent.CLICK, addBox);
}

function playSound(event:Event){
    channel = mySound.play();
    // On next click you want sound to stop so
    // First remove the old listener to avoid play over:  
    newBox.removeEventListener(MouseEvent.CLICK, playSound);
    // and hook listener to stop method
    newBox.addEventListener(MouseEvent.CLICK, stopSound);
 }

 function stopSound(event:Event){
    channel.stop();
    // On next click you want to remove newBox 
    // First remove the old listener to avoid play over:  
    newBox.removeEventListener(MouseEvent.CLICK, stopSound);
    newBox.addEventListener(MouseEvent.CLICK, removeNewBox);
 }

 function removeNewBox(event:Event){
    // First remove the listener :  
    newBox.removeEventListener(MouseEvent.CLICK, removeNewBox );
    removeChild(newBox); // now remove from display list
    newBox = null; // make contents eligible for garbage collection 
 }