This repository has been archived by the owner on Feb 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
controllerModel.js
80 lines (76 loc) · 2.46 KB
/
controllerModel.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
import Controller from "./controller";
import CommandRunner from "./commandRunner";
import { EventEmitter } from "events";
class ControllerModel extends EventEmitter {
constructor() {
super();
// 最初、controllerはunnamedControllerに追加される。
// name がわかると、それが controllers に移行される。
// こうすることで、clientが異なっても、nameが同じ場合、HPなどを共有できるようになる。
// { key: Client, ... }
this.unnamedClients = {};
// { name: Controller, ... }
this.controllers = {};
}
add(key, client) {
this.unnamedClients[key] = client;
this.emit("add", key, client);
}
setName(key, name) {
if (typeof this.unnamedClients[key] === "undefined") {
throw new Error("setNameしようとしたところ、keyに対するclientが見つかりませんでした。 key: " + key);
}
let isNewName = typeof this.controllers[name] === "undefined";
if (isNewName) {
this.controllers[name] = new Controller(name, new CommandRunner(key));
} else if (this.controllers[name].client !== null) {
throw new Error("setNameしようとしましたが、既にclientが存在します。 name: " + name);
}
this.controllers[name].setClient(this.unnamedClients[key]);
delete this.unnamedClients[key];
this.emit("named", key, name, isNewName);
}
removeFromUnnamedClients(key) {
if (this.hasInUnnamedClients(key)) {
delete this.unnamedClients[key];
this.emit("removeUnnamed", key);
}
}
removeClient(name) {
if (this.has(name)) {
this.controllers[name].setClient(null);
this.emit("remove", name);
}
}
hasInUnnamedClients(key) {
return typeof this.unnamedClients[key] !== "undefined";
}
has(name) {
return typeof this.controllers[name] !== "undefined";
}
get(name) {
return this.controllers[name];
}
getAllStates() {
const result = {};
Object.keys(this.controllers).forEach(name => {
result[name] = this.controllers[name].getStates();
});
return result;
}
getUnnamedKeys() {
return Object.keys(this.unnamedClients);
}
toName(key) {
const nameArray = Object.keys(this.controllers).filter(name => {
return this.controllers[name].client !== null &&
this.controllers[name].client.key === key;
});
if (nameArray.length === 1) {
return nameArray[0];
} else {
return null;
}
}
}
export default new ControllerModel();