Event Dispatching
When creating a new class we need to determine where we will place it in our class structure. In this case the Logger class is a utility, so we will add it to a new package called util.
We only want one instance of the Logger class, so we will make it a Singleton to prevent multiple instances from being created.
Listing 6: Logging custom events
package com.studiosedition.util { import flash.events.TextEvent; public class Logger { private static var INSTANCE:Logger; public static function GetInstance():Logger { if(Logger.INSTANCE == null) { Logger.INSTANCE = new Logger(); } return Logger.INSTANCE; } public function Log(e:TextEvent):void { var logText:Array = e.text.split("::"); var date:String = logText[0]; var url:String = logText[1]; // Log the date and url that were clicked e.currentTarget.removeEventListener("textlink", Log); } } }
When the event is dispatched the Logger’s Log method will fire and receive any properties that were set on the event. Since we set the event text to the current date and URL that was selected we will receive those values as the text property of the event parameter.
We can simply split them by our delimiter and handle logging however we deem appropriate. Once we have completed logging the user selection we will remove the listener to prevent any recursion from future textLink events.