我是一个完整的 javascript 新手,如何将前端的 jsTree 与 node.js 中的后端服务集成。后端是使用 Treemodel 库 ( http://jnuno.com/tree-model-js/ ) 编写的。具有附加功能,例如
function getChildren(x)
{
var result=[];
if(x.hasChildren())
{
for(i=0;i<x.children.length;i++)
{
result.push(x.children[i].model);
}
}
return result;
}
和
function expandAll(node) {
console.log(getChildren(node));
for (var t = 0; t < node.children.length; t++) {
if (node.children[t].hasChildren()) {
expandAll(node.children[t]);
}
}
}
我的数据最初是纯文本形式:
var items = [
{'id': 2, 'parentid': 1, 'title': "Delhi"},
{'id': 3, 'parentid': 2, 'title': "CP"},
{'id': 4, 'parentid': 2, 'title': "Saket"},
{'id': 1, 'parentid': 0, 'title': "India"},
{'id': 5, 'parentid': 1, 'title': "Mumbai"},
{'id': 6, 'parentid': 5, 'title': "Andheri"},
{'id': 7, 'parentid': 5, 'title': "Worli"},
{'id': 8, 'parentid': 7, 'title': "Wankhede"}
];
通过使用带有 underscore.js 的以下代码已将其转换为 JSON-
unflatten = function( array, parent, tree ){
tree = typeof tree !== 'undefined' ? tree : [];
parent = typeof parent !== 'undefined' ? parent : { id: 0 };
var children = _.filter( array, function(child){ return child.parentid == parent.id; });
if( !_.isEmpty( children ) ){
if( parent.id == 0 ){
tree = children;
}else{
parent['children'] = children
}
_.each( children, function( child ){ unflatten( array, child ) } );
}
return tree;
}
items = unflatten(items);
我将在前端使用 AJAX 延迟加载实现树结构,类似于:http ://thejackalofjavascript.com/file-browser-with-jstree-angularjs-and-expressjs/
我只需要帮助了解如何使用 TreeModel 实现 jsTree,以及如何使用后端实现的 getChildren 方法进行延迟加载。
谢谢