-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy path6-events.js
More file actions
49 lines (43 loc) · 909 Bytes
/
6-events.js
File metadata and controls
49 lines (43 loc) · 909 Bytes
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
'use strict';
const emitable = (obj, events = {}) => Object.assign(obj, {
on(name, fn) {
const event = events[name] || [];
events[name] = event;
event.push(fn);
},
emit(name, ...data) {
const event = events[name];
if (event) {
for (const fn of event) {
fn(...data);
}
}
}
});
const movable = (obj) => {
obj.on('move', (x, y) => {
console.log('move', x, y);
obj.x += x;
obj.y += y;
obj.emit('moved');
});
return obj;
};
// Usage
const Rect = class {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
toString() {
return `[${this.x}, ${this.y}, ${this.width}, ${this.height}]`;
}
};
const r1 = movable(emitable(new Rect(10, 20, 50, 150)));
console.log(r1.toString());
r1.on('moved', () => {
console.log(r1.toString());
});
r1.emit('move', 10, 20);