1/* 2 * Copyright (C) 2022 Huawei Device 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 16class Event { 17 map: unknown; 18 constructor() { 19 this.map = {}; 20 } 21 22 subscribe(event: string, fn: Function): void { 23 //@ts-ignore 24 this.map[event] = this.map[event] || []; //@ts-ignore 25 this.map[event].push(fn); 26 } 27 publish(event: string, data: unknown): void { 28 //@ts-ignore 29 const fnList = this.map[event] || []; 30 if (!fnList || fnList.length === 0) { 31 return; 32 } 33 fnList.forEach((fn: Function) => fn.call(undefined, data)); 34 } 35 unsubscribe(event: string, fn: Function): void { 36 //@ts-ignore 37 const fnList = this.map[event] || []; 38 const index = fnList.indexOf(fn); 39 if (index < 0) { 40 return; 41 } 42 fnList.splice(index, 1); 43 } 44 subscribeOnce(event: string, callback: Function): void { 45 const f = (data: unknown): void => { 46 callback(data); 47 this.unsubscribe(event, f); 48 }; 49 this.subscribe(event, f); 50 } 51 52 clearTraceRowComplete(): void { 53 //@ts-ignore 54 if (this.map[window.SmartEvent.UI.TraceRowComplete].length > 0) { 55 //@ts-ignore 56 this.map[window.SmartEvent.UI.TraceRowComplete] = []; 57 } 58 } 59} 60 61export const EventCenter = new Event(); 62