as3 删除容器内对象和侦听
1 package com{
2 import flash.display.MovieClip;
3 import flash.events.Event;
4 dynamic public class removeCon extends MovieClip{
5 private var lis:Array;//定义一数组保存侦听
6 public function removeCon() {
7 lis = new Array();
8 addEventListener(Event.REMOVED,remove);//侦听删除事件
9 }
10
11 //重写addEventListener,在增加侦听的时候..把相应的事件保存到数组
12 override public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void {
13 lis.push([type,listener,useCapture]);
14 super.addEventListener(type,listener,useCapture,priority,useWeakReference);
15 }
16
17 //"自我毁灭"的方法
18 private function remove(e:Event):void {
19 if (e.currentTarget!=e.target) {
20 return;
21 }
22 stop();
23 //删除子对象
24 trace("删除前有子对象",numChildren);
25 while (numChildren > 0) {
26 removeChildAt(0);
27 }
28 trace("删除后有子对象",numChildren);
29 //删除动态属性
30 for (var k:String in this) {
31 trace("删除属性",k);
32 delete this[k];
33 }
34
35 //删除侦听
36 trace("num=" + lis.length);
37 for (var i:uint = 0; i < lis.length; i++) {
38 trace("删除Listener", lis[i]);
39 removeEventListener(lis[i][0],lis[i][1],lis[i][2]);
40 }
41 lis=null;
42 }
43 }
44 }
使用方法:
1 import removeCon;
2 var mc:MovieClip = new removeCon();
3 mc.addEventListener(Event.ADDED,aaaa);
4 mc.addEventListener(Event.ADDED_TO_STAGE,aaaa);
5 mc.addEventListener(Event.ENTER_FRAME,aaaa);
6 mc.addEventListener(MouseEvent.CLICK,aaaa);
7 mc.addEventListener(MouseEvent.MOUSE_DOWN,aaaa);
8 mc.a="http://www.manyu.cn/blog";
9 mc.b="我是动态属性2";
10 mc.name="我是MC";
11 addChild(mc);
12 function aaaa(e:Event) {
13
14 }
15 removeChild(mc);
16 mc=null;