1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
|
function WeirdTreeItem(key, object) {
this.subElements = {};
this.count = 0;
this.key = key;
this.object = object;
}
WeirdTreeItem.prototype.getItem = function(keyParts, object) {
if(keyParts.length == 0) {
if(object) {
this.object = object;
}
return this;
}
var top = keyParts.shift();
if(! this.subElements[top]) {
if(! object) return null;
this.subElements[top] = new WeirdTreeItem(top);
this.count++;
}
return this.subElements[top].getItem(keyParts, object);
}
WeirdTreeItem.prototype.addItem = function(object, options) {
options = options || {};
options.keyProp = options.keyProp || null;
options.separator = options.separator || "_";
options.reversed = options.reversed || false;
var key = object;
if(options.keyProp != null) {
key = object[keyProp];
}
var keyParts = key.split(options.separator);
if(options.reversed) {
keyParts.reverse();
}
return this.getItem(keyParts, object);
}
WeirdTreeItem.prototype.draw = function(target) {
if(this.key) {
var li = document.createElement("li");
target.appendChild(li)
li.innerHTML = this.key;
target = li;
}
if(this.count > 0) {
var ul = document.createElement("ul");
target.appendChild(ul);
target = ul;
for(var subElem in this.subElements) {
this.subElements[subElem].draw(target);
}
}
}
WeirdTreeItem.prototype.isValid = function() {
var thisValid = true;
if(this.key) {
thisValid = (this.object != null);
if(! thisValid) {
alert("La clé '" + this.key + "' n'a pas d'objet");
}
}
for(var subElem in this.subElements) {
thisValid &= this.subElements[subElem].isValid();
}
return thisValid;
}
var options = {reversed: true}
var root = new WeirdTreeItem();
root.addItem("b1_a", options);
root.addItem("b2_a", options);
root.addItem("b3_a", options);
root.addItem("c1_b1_a", options);
root.addItem("c2_b1_a", options);
root.addItem("c1_b2_a", options);
root.addItem("c2_b2_a", options);
root.addItem("d1_c2_b2_a", options);
root.addItem("e1_d1_c2_b2_a", options);
root.addItem("d1_c1_b1_a", options);
root.addItem("f2_e1_d1_c2_b2_a", options);
//root.isValid();
root.draw(document.body); |
Partager