]>
Commit | Line | Data |
---|---|---|
1 | /* | |
2 | * Node Collections contain nodes, in order to keep the lists of nodes | |
3 | * that belong to each type. | |
4 | * | |
5 | * It has a type which is the class name of the node, and an array of | |
6 | * instances of that class. | |
7 | */ | |
8 | ||
9 | export class NodeCollection extends EventTarget { | |
10 | ||
11 | constructor(config) { | |
12 | ||
13 | super(); | |
14 | ||
15 | this.nodes = []; | |
16 | this.type = null; | |
17 | ||
18 | Object.assign(this, config); | |
19 | } | |
20 | ||
21 | /* | |
22 | * Creates a node for an entity if it matches, and adds it to the | |
23 | * node list. | |
24 | * | |
25 | * Returns true if added, false otherwise. | |
26 | */ | |
27 | add(entity) { | |
28 | ||
29 | if (this.type.matches(entity) && !this._entityExists(entity)) { | |
30 | ||
31 | const node = new this.type({}); | |
32 | const types = this.type.types; | |
33 | const typeNames = Object.keys(types); | |
34 | ||
35 | node.entity = entity; | |
36 | ||
37 | for (const typeName of typeNames) { | |
38 | node[typeName] = entity.getComponent(types[typeName]); | |
39 | } | |
40 | ||
41 | this.nodes.push(node); | |
42 | const event = new Event('nodeAdded'); | |
43 | event.node = node; | |
44 | this.dispatchEvent(event); | |
45 | ||
46 | return true; | |
47 | } | |
48 | ||
49 | return false; | |
50 | } | |
51 | ||
52 | /* | |
53 | * Removes an entity by removing its related node from the list of nodes | |
54 | * | |
55 | * returns true if it was removed, false otherwise. | |
56 | */ | |
57 | remove(entity) { | |
58 | ||
59 | let foundIndex = -1; | |
60 | let foundNode = null; | |
61 | ||
62 | const found = this.nodes.some((node, i) => { | |
63 | ||
64 | if (node.entity === entity) { | |
65 | foundIndex = i; | |
66 | foundNode = node; | |
67 | return true; | |
68 | } | |
69 | }); | |
70 | ||
71 | if (found) { | |
72 | this.nodes.splice(foundIndex, 1); | |
73 | const event = new Event('nodeRemoved'); | |
74 | event.node = foundNode; | |
75 | this.dispatchEvent(event); | |
76 | } | |
77 | ||
78 | return found; | |
79 | } | |
80 | ||
81 | /* | |
82 | * Checks whether we already have nodes for this entity. | |
83 | */ | |
84 | _entityExists(entity) { | |
85 | ||
86 | return this.nodes.some((node) => node.entity === entity); | |
87 | } | |
88 | } | |
89 | ||
90 | ||
91 | /* | |
92 | * Make the node collection iterable without returning the array directly | |
93 | */ | |
94 | NodeCollection.prototype[Symbol.iterator] = function * () { | |
95 | ||
96 | yield* this.nodes; | |
97 | }; |