summaryrefslogtreecommitdiff
path: root/ofborg/ofborg-viewer/src/mixins/eventable.js
blob: a33e8edafd8142cd3c8570ae2f8ecf2e64fbfd7b (plain)
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import each from "lodash/each";
import pull from "lodash/pull";

/**
 * Adds functions looking like the EventTarget ones on `this`.
 *
 * This is NOT compatible, as they are not using Event.
 * They cannot preventDefault.
 * They cannot stop propagation.
 * There is no propagation.
 */
const eventable = (self) => {
	each(
		// Functions to mix in.
		{
			addEventListener(type, listener) {
				if (!this[`_${type}_listeners`]) {
					this[`_${type}_listeners`] = [];
				}
				const table = this[`_${type}_listeners`];

				table.push(listener);
			},
			removeEventListener(type, listener) {
				if (!this[`_${type}_listeners`]) {
					this[`_${type}_listeners`] = {};
				}
				const table = this[`_${type}_listeners`];

				pull(table, listener);
			},
			sendEvent(type, ...params) {
				if (!this[`_${type}_listeners`]) {
					this[`_${type}_listeners`] = [];
				}
				const table = this[`_${type}_listeners`];

				table.forEach((fn) => fn(...params));
			}
		},
		// Mixing in all those.
		(fn, name) => {
			self[name] = fn.bind(self);
		}
	);
};

export default eventable;