-
Notifications
You must be signed in to change notification settings - Fork 1
/
avatar-manager.js
97 lines (85 loc) · 2.43 KB
/
avatar-manager.js
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
avatar manager forwards avatar related events from local player
this is an utility class, to smoothly support same interface
even when local player is changed on party player switch
*/
import {playersManager} from './players-manager';
class AvatarManager extends EventTarget {
constructor() {
super();
this.cleanup = null;
const playerSelectedFn = e => {
const {oldPlayer, player} = e.data;
if (oldPlayer) {
this.unbindPlayer(oldPlayer);
}
this.bindPlayer(player);
};
playersManager.addEventListener('playerchange', playerSelectedFn);
this.removeListenerFn = () => {
playersManager.removeEventListener('playerchange', playerSelectedFn);
};
// this is the initial event for the first player
const localPlayer = playersManager.getLocalPlayer();
this.bindPlayer(localPlayer);
}
bindPlayer(player) {
this.player = player;
// forward player messages on player change
const avatarchange = e => {
this.dispatchEvent(
new MessageEvent('avatarchange', {
data: e,
}),
);
};
player.addEventListener('avatarchange', avatarchange);
const actionupdate = e => {
this.dispatchEvent(
new MessageEvent('actionupdate', {
data: e,
}),
);
};
const actionadd = e => {
this.dispatchEvent(
new MessageEvent('actionadd', {
data: e,
}),
);
};
const actionremove = e => {
this.dispatchEvent(
new MessageEvent('actionremove', {
data: e,
}),
);
};
player.addEventListener('actionadd', actionupdate);
player.addEventListener('actionadd', actionadd);
player.addEventListener('actionremove', actionupdate);
player.addEventListener('actionremove', actionremove);
this.cleanup = () => {
player.removeEventListener('avatarchange', avatarchange);
player.removeEventListener('actionadd', actionupdate);
player.removeEventListener('actionremove', actionupdate);
player.removeEventListener('actionadd', actionadd);
player.removeEventListener('actionremove', actionremove);
};
}
unbindPlayer(player) {
if (this.cleanup) {
this.cleanup();
this.cleanup = null;
}
}
destroy() {
if (this.cleanup) {
this.cleanup();
this.cleanup = null;
}
this.removeListenerFn();
}
}
const avatarManager = new AvatarManager();
export {avatarManager};