]>
git.r.bdr.sh - rbdr/serpentity/blob - lib/serpentity/node_collection.js
deeb26deae1dc155ab4e19ade7e382d425548006
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.
64 const found
= this.nodes
.some((node
, i
) => {
66 if (node
.entity
=== entity
) {
74 this.nodes
.splice(foundIndex
, 1);
75 this.emit('nodeRemoved', { foundNode
});
82 * Checks whether we already have nodes for this entity.
84 _entityExists(entity
) {
88 for (const node
of this.nodes
) {
89 if (node
.entity
=== entity
) {
100 * Make the node collection iterable without returning the array directly
102 NodeCollection
.prototype[Symbol
.iterator
] = function * () {
107 module
.exports
= NodeCollection
;