2010-12-08 133 views
1

可以說我有一個Ext.tree.TreePanel對象,它已經從外部文件加載的數據,例如:獲取JSON數據

var tree = new Ext.tree.TreePanel({ 
    ... 
    loader: new Ext.tree.TreeLoader({ 
     dataUrl:'./some_file.json' 
    }), 
    ... 
}); 

此文件是定義對象數組樹。

假設用戶向樹添加新節點並移動一些節點。是否需要從樹中獲取JSON數據,以便下次用戶加載樹時使用它?

EDIT(代碼解決方案)

這是基於從娟的反應想法的解決方案。我正在把這件事情在任何人發現這個線程在未來,並正在尋找一些代碼。

function getNodeList(bfsQueue) { 
    var node = bfsQueue.pop(); 
    var nodeQueue = []; 

    for (var ii = 0; ii < node.childNodes.length; ii++) { 
     bfsQueue.push(node.childNodes[ii]); 
     nodeQueue.push(node.childNodes[ii]); 
    } 
    if (bfsQueue.length === 0) { 
     return nodeQueue; 
    } else { 
     return nodeQueue.concat(getNodeList(bfsQueue)); 
    } 
} 

var startQueue = []; 
var nodeList = []; 

startQueue.push(tree.getRootNode()); 
nodeList.push(tree.getRootNode()); 
nodeList = nodeList.concat(getNodeList(startQueue)); 
console.dir(nodeList); 

for (var nn = nodeList.length-1; nn >= 0; nn--) { 

    var params = []; 
    for (var pp in nodeList[nn].attributes) { 
     if (pp === "children" || pp === "loader") {continue;} 
     params.push('"' + pp + '":' + JSON.stringify(nodeList[nn].attributes[pp]) + ''); 
    } 

    if (nodeList[nn].childNodes.length > 0) { 
     var childList = []; 

     for (var ii = 0; ii < nodeList[nn].childNodes.length; ii++) { 
      childList.push(nodeList[nn].childNodes[ii].json); 
     } 

     params.push('"children": [' + childList.join(',') + ']'); 
    } 

    nodeList[nn].json = "{" + params.join(",") + "}"; 
} 

console.log(nodeList[0].json); // root node 

回答

1

首先,你真正想要的是attributes屬性,它是用來創建節點的JSON。最相關的屬性會更新,但childNodes不是。所以你必須寫點東西讓它回來。

通過使用childNodes遍歷樹,你可以獲得所有的節點。你需要將它們重新組裝成一個單一的JSON。

Ext.data.Node.prototype.getJson = function() { 
     // Should deep copy so we don't affect the tree 
     var json = this.attributes; 

     json.children = []; 
     for (var i=0; i < node.childNodes.length; i++) { 
      json.children.push(node.childNodes[i].getJson()) 
     } 
     return json; 
} 

tree.getRootNode().getJson(); 

這個例子並不完美,但應該給你足夠的開始。

更新

在EXT-JS 4.0節點現在都裝修成Records。因此,應通過記錄/模型接口記錄所有額外屬性,並使用getset方法檢索集

+0

我不知道屬性屬性。那和childNodes數組正是我所需要的。謝謝你的信息! – patorjk 2010-12-08 23:03:11

0

在最新的ExtJS版本中,樹節點的NodeInterface具有這樣的序列化函數。也許這與你有關。