Last active
October 11, 2015 17:08
-
-
Save lynxerzhang/3891805 to your computer and use it in GitHub Desktop.
Delegate test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package | |
{ | |
import flash.events.IEventDispatcher; | |
import flash.utils.Dictionary; | |
/** | |
* @inspired from 'Bumpslide ActionScript Library' s Delegate class | |
* TODO | |
*/ | |
public class Delegate | |
{ | |
public function Delegate() | |
{ | |
} | |
/** | |
* add specfied event listener | |
*/ | |
public static function addListener(target:IEventDispatcher, evtName:String, listener:Function, ...args):void{ | |
if (!listenerDict[target]) { | |
listenerDict[target] = []; | |
} | |
var d:Function = createEventDelegate.apply(null, [listener].concat(args)); | |
var o:Object = {"listener":d, "name":evtName, "rawListener":listener}; | |
listenerDict[target].push.apply(null, [o]); | |
target.addEventListener(evtName, d); | |
} | |
private static const listenerDict:Dictionary = new Dictionary(false); | |
private static function createEventDelegate(listener:Function, ...listenerArgs):Function { | |
return function(...args):void { | |
listener.apply(null, args.concat(listenerArgs)); | |
} | |
} | |
/** | |
* remove specfied event listener | |
* @param target | |
* @param evtName | |
* @param listener | |
*/ | |
public static function removeListener(target:IEventDispatcher, evtName:String, listener:Function):void { | |
var k:Array = listenerDict[target]; | |
if (k) { | |
var delIndex:int = -1; | |
var delItem:Object; | |
k.some(function(item:Object, ...args):Boolean { | |
if (item["rawListener"] == listener && item["name"] == evtName) { | |
delIndex = args[0]; | |
delItem = item; | |
return true; | |
} | |
return false; | |
}); | |
if (delItem) { | |
k.splice(delIndex, 1); | |
var len:int = k.length; | |
if (len == 0) { | |
delete listenerDict[target]; | |
} | |
target.removeEventListener(evtName, delItem["listener"]); | |
} | |
} | |
} | |
/** | |
* remove all target's listener | |
*/ | |
public static function removeAllListener(target:IEventDispatcher):void { | |
var k:Array = listenerDict[target]; | |
if (k) { | |
k.forEach(function(item:Object, ...args):void { | |
target.removeEventListener(item["name"], item["listener"]); | |
}); | |
k.length = 0; | |
delete listenerDict[target]; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment