• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
16export class Broadcast {
17    private callBackArray = [];
18
19    constructor() {
20    }
21
22    public on(event, callback) {
23        (this.callBackArray[event] || (this.callBackArray[event] = [])).push(callback);
24    }
25
26    public off(event, callback) {
27        if (event == null) {
28            this.callBackArray = [];
29        }
30
31        const cbs = this.callBackArray[event];
32        if (!cbs) {
33            return;
34        }
35        if (callback == null) {
36            this.callBackArray[event] = null;
37        }
38        let cb;
39        let l = cbs.length;
40        for (let i = 0; i < l; i++) {
41            cb = cbs[i];
42            if (cb === callback || cb.fn === callback) {
43                cbs.splice(i, 1);
44                break;
45            }
46        }
47    }
48
49    public emit(event, args: any[]) {
50        let _self = this;
51        if (!this.callBackArray[event]) {
52            return;
53        }
54        let cbs = [...this.callBackArray[event]];
55        if (cbs) {
56            let l = cbs.length;
57            for (let i = 0; i < l; i++) {
58                try {
59                    cbs[i].apply(_self, args);
60                } catch (e) {
61                    new Error(e);
62                }
63            }
64        }
65    }
66
67    public release() {
68        this.callBackArray.forEach((array) => {
69            array.length = 0;
70        });
71        this.callBackArray.length = 0;
72        this.callBackArray = [];
73    }
74}