]> git.r.bdr.sh - rbdr/serpentity/blob - lib/serpentity/node_collection.js
d1d25fc1fb33d8560dc5913dcde419405de75f3f
[rbdr/serpentity] / lib / serpentity / node_collection.js
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 Class(Serpentity, "NodeCollection")({
9 prototype : {
10 type : null,
11 nodes : null,
12
13 init : function init(config) {
14 var property;
15
16 config = config || {};
17
18 this.nodes = [];
19
20 for (property in config) {
21 if (config.hasOwnProperty(property)) {
22 this[property] = config[property];
23 }
24 }
25 },
26
27 /*
28 * Creates a node for an entity if it matches, and adds it to the
29 * node list.
30 *
31 * Returns true if added, false otherwise.
32 */
33 add : function add(entity) {
34 var node, types, property;
35
36 if (this.type.matches(entity) && !this._entityExists(entity)) {
37 node = new this.type({});
38
39 node.entity = entity;
40
41 types = this.type.types;
42
43 for (property in types) {
44 if (types.hasOwnProperty(property)) {
45 node[property] = entity.getComponent(types[property]);
46 }
47 }
48
49 this.nodes.push(node);
50
51 return true;
52 }
53
54 return false;
55 },
56
57 /*
58 * Removes an entity by removing its related node from the list of nodes
59 *
60 * returns true if it was removed, false otherwise.
61 */
62 remove : function (entity) {
63 var found;
64 found = -1;
65 this.nodes.forEach(function (node, i) {
66 if (node.entity === entity) {
67 found = i;
68 }
69 });
70
71 if (found >= 0) {
72 this.nodes.splice(found, 1);
73 return true;
74 }
75
76 return false;
77 },
78
79 /*
80 * Checks whether we already have nodes for this entity.
81 */
82 _entityExists : function entityExists(entity) {
83 var found;
84 found = false;
85 this.nodes.forEach(function (node) {
86 if (node.entity === entity) {
87 found = true;
88 }
89 });
90
91 return found;
92 }
93 }
94 });