BasicEventManager.jsx 988 Bytes
Newer Older
Tamas Kecskes's avatar
Tamas Kecskes committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
 * @author kecso / https://github.com/kecso
 */
export default class BasicEventManager {
    constructor() {
        this.subscribers = {};
        this.lastEvents = {};

        this.subscribe = this.subscribe.bind(this);
        this.unsubscribe = this.unsubscribe.bind(this);
        this.fire = this.fire.bind(this);
    }

    fire(id, event) {
        const oldEvent = this.lastEvents[id];
        this.lastEvents[id] = event;
        if (JSON.stringify(oldEvent) !== JSON.stringify(event)) {
            (this.subscribers[id] || []).forEach((eventFn) => {
                eventFn(id, event);
            });
        }
    }

    subscribe(id, eventFn) {
        this.subscribers[id] = this.subscribers[id] || [];
        this.subscribers[id].push(eventFn);
        return this.lastEvents[id];
    }

    unsubscribe(id, eventFn) {
        this.subscribers[id] = this.subscribers[id] || [];
        this.subscribers[id].splice(this.subscribers[id].indexOf(eventFn), 1);
    }
}