]>
git.r.bdr.sh - rbdr/serpentity/blob - lib/serpentity/node_collection.js
e6150201afb82ced47171ae8af76daf1709f3b8f
1 import Events
from 'events';
4 * Node Collections contain nodes, in order to keep the lists of nodes
5 * that belong to each type.
7 * It has a type which is the class name of the node, and an array of
8 * instances of that class.
11 export class NodeCollection
extends Events
{
20 Object
.assign(this, config
);
24 * Creates a node for an entity if it matches, and adds it to the
27 * Returns true if added, false otherwise.
31 if (this.type
.matches(entity
) && !this._entityExists(entity
)) {
33 const node
= new this.type({});
34 const types
= this.type
.types
;
35 const typeNames
= Object
.keys(types
);
39 for (const typeName
of typeNames
) {
40 node
[typeName
] = entity
.getComponent(types
[typeName
]);
43 this.nodes
.push(node
);
44 this.emit('nodeAdded', { node
});
53 * Removes an entity by removing its related node from the list of nodes
55 * returns true if it was removed, false otherwise.
62 const found
= this.nodes
.some((node
, i
) => {
64 if (node
.entity
=== entity
) {
72 this.nodes
.splice(foundIndex
, 1);
73 this.emit('nodeRemoved', { node: foundNode
});
80 * Checks whether we already have nodes for this entity.
82 _entityExists(entity
) {
86 for (const node
of this.nodes
) {
87 if (node
.entity
=== entity
) {
98 * Make the node collection iterable without returning the array directly
100 NodeCollection
.prototype[Symbol
.iterator
] = function * () {