xref: /MusicFree/src/lib/react-native-vdebug/src/event.js (revision 5589cdf32b2bb0f641e5ac7bf1f6152cd6b9b70e)
1export default class Event {
2    constructor() {
3        this.eventList = {};
4    }
5
6    on(eventName, callback) {
7        if (!this.eventList[eventName]) {
8            this.eventList[eventName] = [];
9        }
10        this.eventList[eventName].push(callback);
11        return this;
12    }
13
14    trigger(...args) {
15        const key = Array.prototype.shift.call(args);
16        const fns = this.eventList[key];
17        if (!fns || fns.length === 0) {
18            return this;
19        }
20        for (let i = 0, fn; (fn = fns[i++]); ) {
21            fn.apply(this, args);
22        }
23        return this;
24    }
25
26    off(key, fn) {
27        const fns = this.eventList[key];
28        if (!fns) {
29            return this;
30        }
31        if (!fn) {
32            if (fns) {
33                fns.length = 0;
34            }
35        } else {
36            for (let i = fns.length - 1; i >= 0; i--) {
37                const _fn = fns[i];
38                if (_fn === fn) {
39                    fns.splice(i, 1);
40                }
41            }
42        }
43        return this;
44    }
45}
46let event;
47module.exports = (function () {
48    if (!event) {
49        event = new Event();
50    }
51    return event;
52})();
53