Archive for August, 2007

关于as3事件的笔记

Friday, August 17th, 2007

as2时代直接在dispatchEvent的时候跟上想跟的参数就可以了,as3增加了一个Event的继承类来承担其中的信息传递,不过看书看到关键时刻居然就没有了。于是笔记一下类实例怎么向外发送事件和传递参数,来点实用的。
发送事件的Guest,在Guest内发送”do_b”的Event:

  1. var e:GuestEvent = new GuestEvent(GuestEvent.DO_B);
  2. e.args = {author:"hirokimo",time:"21:10"};
  3. this.dispatchEvent(e);

这时候为了传递参数,使用一个继承Event的自定义事件类GuestEvent:

  1. package
  2. {
  3.     import flash.events.Event;   
  4.     public class GuestEvent extends Event
  5.     {
  6.         public static const DO_A:String = "do_a";
  7.         public static const DO_B:String = "do_b";
  8.         public static const DO_C:String = "do_c";      
  9.         public var args:*;   
  10.         public function GuestEvent(_type:String)
  11.         {
  12.             super(_type);
  13.         }
  14.     }
  15. }

最后,在类外面添加侦听和接收的地方:

  1. package
  2. {
  3.     public class EventTest
  4.     {
  5.         public function EventTest()
  6.         {
  7.             var guest:Guest = new Guest();
  8.             guest.addEventListener(GuestEvent.DO_B,handleB);
  9.         }
  10.         private function handleB(e:GuestEvent):void
  11.         {
  12.             trace("author:"+e.args.author
  13.             +" time:"+e.args.time);
  14.             //author:hirokimo time:21:10
  15.         }
  16.     }
  17. }

大功告成,之后就可以顺利的发送事件参数了。
不过有一点值得注意:Guest类里有时需要在初始化后直接dispatch一个Event出来,这时候因为外部addEventListener动作还没有完成,listener是收不到事件的。
这个问题很容易被忽略,如果一定要这么做,可以:
1.Guest初始化后timer几百毫秒再dispatch 或者
2.外面addEventListener完之后,主动调guest.xxx来发送。

as3 读书笔记

Sunday, August 5th, 2007

仅仅是笔记 没有讨论问题 大家请略过

1.用正则来replace字符串

  1. var str:String = "above thE cloud,around The shadow.";
  2. var pattern:RegExp = /the/ig;
  3. trace(str.replace(pattern, "my"));
  4. //above my cloud,around my shadow.

2.数组深度copy

  1. private function clone(source:Object):*
  2. { 
  3.     var myBA:ByteArray = new ByteArray();
  4.     myBA.writeObject(source);
  5.     myBA.position = 0;
  6.     return(myBA.readObject());
  7. }

3.遍历Object,这个和as3没什么关系,不过经常用到。

  1. private function traceObject(obj:Object, indent:uint = 0):void
  2. {
  3.     var indentString:String = "";
  4.     var i:uint;
  5.     var prop:String;
  6.     var val:*;
  7.     for (i = 0; i < indent; i++)
  8.     {
  9.         indentString += "\t";
  10.     }
  11.     for (prop in obj)
  12.     {
  13.         val = obj[prop];
  14.         if (typeof(val) == "object") 
  15.         {
  16.             trace(indentString + " " + prop + ": [Object]");
  17.             traceObject(val, indent + 1);
  18.         }
  19.         else
  20.         {
  21.             trace(indentString + " " + prop + ": " + val);
  22.         }
  23.     }
  24. }