Create addFlashEventListener method for javaScript
snipped by jspooner
Allow javaScript to register event listeners to flash.
package com.xxx.javascript { import com.xxx.xxx_internal; import flash.external.ExternalInterface; use namespace xxx_internal; public class JsEventDispatcher { public static const PCATS_LOADED:String = "pcatsLoaded"; private static var _instance:JsEventDispatcher; private var _hash:Object; public static function getInstance():JsEventDispatcher { if( _instance == null ) { _instance = new JsEventDispatcher( new SingletonEnforcer() ); } return _instance; } public function dispatchEvent(type:String, e:Object=null):Boolean { if ( _hash.hasOwnProperty(type) ) { var l:int = _hash[type].length; var x:int = 0; for(x; x < l; x++) { trace("[info] Invoking JavaScript",_hash[type][x],e); if( ExternalInterface.available ) { ExternalInterface.call(_hash[type][x],e); } } return true; } return false; } public function JsEventDispatcher(enforcer:SingletonEnforcer) { _hash = new Object; if(ExternalInterface.available) { ExternalInterface.addCallback( "addFlashEventListener", addFlashEventListener); ExternalInterface.addCallback( "hasFlashEventListener", hasFlashEventListener); } } xxx_internal function addFlashEventListener(type:String, callBack:String):void { if ( _hash.hasOwnProperty(type) ) { _hash[type].push(callBack); } else { _hash[type] = new Array(callBack); } } xxx_internal function hasFlashEventListener(type:String):Boolean { if(_hash.hasOwnProperty(type) ) return true; return false; } } } class SingletonEnforcer { } JsEventDispatcherTest.as package com.xxx.javascript { import com.xxx.xxx_internal; import asunit.framework.*; import flash.errors.MemoryError; use namespace xxx_internal; public class JsEventDispatcherTest extends TestCase { private var instance:JsEventDispatcher; public function JsEventDispatcherTest(methodName:String=null) { super(methodName) } override protected function setUp():void { super.setUp(); instance = JsEventDispatcher.getInstance(); } override protected function tearDown():void { super.tearDown(); instance = null; } public function testInstantiated():void { assertTrue("instance is JsEventDispatcher", instance is JsEventDispatcher); } public function testFail():void { var type:String = "pcatsLoaded"; var callback:String = "handlePcats"; instance.addFlashEventListener( type, callback ); assertFalse("Should have not have a listener for " + type, instance.hasFlashEventListener("fail") ); } public function testPass1():void { var type:String = "pcatsLoaded"; var callback:String = "handlePcats"; instance.addFlashEventListener( type, callback ); assertTrue("Should have not have a listener for " + type, instance.hasFlashEventListener( type ) ); } public function testCall():void { var type:String = "pcatsLoaded"; var callback:String = "handlePcats"; instance.addFlashEventListener( type, callback ); assertTrue("Should have not have a listener for " + type, instance.dispatchEvent(type) ); } } }




