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: any; 18 constructor() { 19 this.map = {}; 20 } 21 22 subscribe(event: string, fn: Function) { 23 this.map[event] = this.map[event] || []; 24 this.map[event].push(fn); 25 } 26 publish(event: string, data: any) { 27 const fnList = this.map[event] || []; 28 if (!fnList || fnList.length === 0) return; 29 fnList.forEach((fn: Function) => fn.call(undefined, data)); 30 } 31 unsubscribe(event: string, fn: Function) { 32 const fnList = this.map[event] || []; 33 const index = fnList.indexOf(fn); 34 if (index < 0) return; 35 fnList.splice(index, 1); 36 } 37 subscribeOnce(event: string, callback: Function) { 38 const f = (data: any) => { 39 callback(data); 40 this.unsubscribe(event, f); 41 }; 42 this.subscribe(event, f); 43 } 44 45 clearTraceRowComplete() { 46 if (this.map[window.SmartEvent.UI.TraceRowComplete].length > 0) { 47 this.map[window.SmartEvent.UI.TraceRowComplete] = []; 48 } 49 } 50} 51 52export const EventCenter = new Event(); 53