1/*
2 * Copyright (c) 2022-2023 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
16export class BroadCast {
17  private callBackArray: Map<string, Function[]> = new Map();
18
19  constructor() {
20  }
21
22  public on(event: string, callback: Function): void {
23    let cbs = this.callBackArray.get(event);
24    if (!cbs) {
25      cbs = new Array<Function>();
26      this.callBackArray.set(event, cbs);
27    }
28    cbs.push(callback);
29  }
30
31  public off(event: string, callback?: Function): void {
32    if (!event) {
33      this.callBackArray = new Map();
34      return;
35    }
36    if (!callback) {
37      this.callBackArray.delete(event);
38      return;
39    }
40
41    const cbs = this.callBackArray.get(event);
42    if (!cbs) {
43      return;
44    }
45    let length = cbs.length;
46    for (let i = 0; i < length; i++) {
47      let cb = cbs[i];
48      if (cb === callback) {
49        cbs.splice(i, 1);
50        break;
51      }
52    }
53  }
54
55  public emit(event: string, args: unknown[]): void {
56    let cbs = this.callBackArray.get(event);
57    if (!cbs) {
58      return;
59    }
60    let l = cbs.length;
61    for (let i = 0; i < l; i++) {
62      try {
63        cbs[i].apply(this, args);
64      } catch (e) {
65        new Error(e);
66      }
67    }
68  }
69
70  public release(): void {
71    this.callBackArray.clear();
72  }
73}