123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- class Listener{
-
- private _event: string = '';
-
- private _callback: Function = null;
-
- private _callTarget: any = null;
- constructor(ev: string, callback: Function, target: any = null){
- this._event = ev;
- this._callback = callback;
- this._callTarget = target;
- }
- hasCallBack(func: Function){
- return this._callback === func;
- }
- callback(...args){
- this._callback.apply(this._callTarget,[...args]);
- }
- }
- class MessageMgr{
- static instance: MessageMgr = null;
-
- private _listeners: Map<string, Listener[]> = new Map();
-
- addEvent(ev: string, callback: Function, target: any = null){
- const lis: Listener = new Listener(ev, callback, target);
- if(this._listeners.has(ev)){
-
- this._listeners.get(ev).push(lis);
- return;
- }
-
-
- const liss: Listener[] = [];
-
- liss.push(lis);
-
- this._listeners.set(ev, liss);
- }
-
- dispatch(event: string, ...args){
- this._listeners.forEach((liss: Listener[], ev: string)=>{
-
- if(event === ev){
- for(const lis of liss){
- lis.callback(...args);
- }
- }
- })
- }
-
- removeEvent(event: string | Function){
- if(typeof(event) === "string"){
- this._listeners.delete(event);
- return;
- }
- for(const liss of Array.from(this._listeners.values())){
- for(let i = 0; i < liss.length; i++){
- if(liss[i].hasCallBack(event)){
- liss.splice(i , 1);
- return;
- }
- }
- }
- }
-
- removeAll(){
- this._listeners.clear();
- }
- }
- export const messageMgr: MessageMgr = MessageMgr.instance = new MessageMgr();
|