-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathevent-target.js
More file actions
53 lines (42 loc) · 1.04 KB
/
event-target.js
File metadata and controls
53 lines (42 loc) · 1.04 KB
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
49
50
51
52
53
'use strict';
class PointEvent extends Event {
constructor(type, detail = {}) {
super(type);
this.detail = detail;
this.result = undefined;
}
}
class Point {
#x;
#y;
#target;
constructor({ x, y }) {
this.#x = x;
this.#y = y;
this.#target = new EventTarget();
this.#target.addEventListener('move', (e) => {
const { x: dx, y: dy } = e.detail;
this.#x += dx;
this.#y += dy;
e.result = this;
});
this.#target.addEventListener('clone', (e) => {
e.result = new Point({ x: this.#x, y: this.#y });
});
this.#target.addEventListener('toString', (e) => {
e.result = `(${this.#x}, ${this.#y})`;
});
}
emit(type, detail = {}) {
const event = new PointEvent(type, detail);
this.#target.dispatchEvent(event);
return event.result;
}
}
// Usage
const p1 = new Point({ x: 10, y: 20 });
console.log(p1.emit('toString'));
const c1 = p1.emit('clone');
console.log(c1.emit('toString'));
c1.emit('move', { x: -5, y: 10 });
console.log(c1.emit('toString'));