]>
git.r.bdr.sh - rbdr/serpentity/blob - lib/serpentity/node_collection.js
7c2c627e13424acf4ca880f6cf90f1be0e964ce5
3 const Events
= require('events');
6 * Node Collections contain nodes, in order to keep the lists of nodes
7 * that belong to each type.
9 * It has a type which is the class name of the node, and an array of
10 * instances of that class.
13 const NodeCollection
= class NodeCollection
extends Events
{
22 Object
.assign(this, config
);
26 * Creates a node for an entity if it matches, and adds it to the
29 * Returns true if added, false otherwise.
33 if (this.type
.matches(entity
) && !this._entityExists(entity
)) {
35 const node
= new this.type({});
36 const types
= this.type
.types
;
37 const typeNames
= Object
.keys(types
);
41 for (const typeName
of typeNames
) {
42 node
[typeName
] = entity
.getComponent(types
[typeName
]);
45 this.nodes
.push(node
);
46 this.emit('nodeAdded', { node
});
55 * Removes an entity by removing its related node from the list of nodes
57 * returns true if it was removed, false otherwise.
63 const found
= this.nodes
.some((node
, i
) => {
65 if (node
.entity
=== entity
) {
72 this.nodes
.splice(foundIndex
, 1);
73 this.emit('nodeRemoved', { node
});
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 * () {
105 module
.exports
= NodeCollection
;