Qi Nodes
http://drkibitz.github.io/qi-nodes/
Base implementation for composite patterns in JavaScript.
Usage
Any object with its property of "root" set, qualifies as a rooted node. The root property is simply propagated up and down the leaves.
The module itself is a rooted NodeObject.
var nodes = ;console;// > true
The previous fact doesn't limit you from having more rooted trees.
var root = nodes;console;// > false
There are many ways to work with the API, but they follow the same pattern.
// pretty straight forwardn1 = root;n2 = nodes; // The last argument is always the node contextn3 = nodes; // In this case it's the parentn4 = nodes; // In this case it's the child // Automatically append a newly created node by passing the parent to the create method.n5 = nodes; // > root -> n1, n2, n3, n4, n5, n6
Use instances of NodeObject to automatically use "this" as the node context. Which means the default value of the last optional argument in methods (With the exception of the create method), will be itself.
var singleNode = nodes;n3 = singleNode;// root -> n1, n2, singleNode, n4, n5, n6
The API works with generic objects. This is possible because members are simply property based. The only reason to use or extend the NodeObject constructor is if you like that flavor of API.
var root2 = nodes n2_1 = nodes n2_2 = nodes n2_3 = nodes;// root2 -> n2_1 -> n2_2 -> n2_3 n2_3 = nodes;// root2 -> n2_3 -> n2_2 -> n2_1
Create a class that extends NodeObject as normal.
{}MyNodeExtendedprototype = Object
Assign (mixin) the NodeObject prototype.
{}Object; var root = MyNodeAssignedprototype;var node = root; console; // trueconsole; // true
Swap nodes from one tree to another.
var root3 = nodes; n3_1 = nodes n3_2 = nodes n3_3 = nodes;// root3 -> n3_1 -> n3_2 -> n3_3 n2_2 = n3_2;// root2 -> n2_3 -> n3_2 -> n2_1// root3 -> n3_1 -> n2_2 -> n3_3