1/* 2 * Copyright (c) 2023 Shenzhen Kaihong Digital Industry Development Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16type CallbackType = Function; 17 18export class Broadcast { 19 private callBackArray: Map<string, CallbackType[]> = new Map<string, CallbackType[]>(); 20 21 constructor() { 22 } 23 24 public on(event: string, callback: CallbackType): void { 25 if (this.callBackArray.get(event) === null || this.callBackArray.get(event) === undefined) { 26 this.callBackArray.set(event, []); 27 } 28 this.callBackArray.get(event).push(callback); 29 } 30 31 public off(event: string | null, callback: CallbackType | null): void { 32 if (event == null) { 33 this.callBackArray.clear(); 34 } 35 36 const cbs: CallbackType[] = this.callBackArray.get(event); 37 if (!Boolean<Function[]>(cbs).valueOf()) { 38 return; 39 } 40 if (callback == null) { 41 this.callBackArray.set(event, null); 42 } 43 let cb; 44 let l = cbs.length; 45 for (let i = 0; i < l; i++) { 46 cb = cbs[i]; 47 if (cb === callback || cb.fn === callback) { 48 cbs.splice(i, 1); 49 break; 50 } 51 } 52 } 53 54 public emit(event: string, args: Object[]): void { 55 let _self = this; 56 if (!Boolean<Function[]>(this.callBackArray.get(event)).valueOf()) { 57 return; 58 } 59 60 let cbs: CallbackType[] = []; 61 for (let i = 0; i < this.callBackArray.get(event).length; i++) { 62 cbs.push(this.callBackArray.get(event)[i]) 63 } 64 65 if (cbs != null) { 66 let l = cbs.length; 67 for (let i = 0; i < l; i++) { 68 try { 69 cbs[i].apply(_self, args); 70 } catch (e) { 71 new Error(e); 72 } 73 } 74 } 75 } 76 77 public release(): void { 78 this.callBackArray.forEach((array: Object[]): void => { 79 array.length = 0; 80 }); 81 this.callBackArray.clear(); 82 } 83} 84