jsTree排序功能回收

时间:2020-06-05 15:13:11

标签: javascript sorting jstree

我手上有多个 jstrees 。我为每个插件添加了sort插件并进行了配置:

  "core": { .. },
  "plugins": ['sort', ..],
  "sort": action_sort,
  ...

然后我继续编写以下有问题的函数:

/** @param id_node{1,2}: Despite of what can be read here: https://www.jstree.com/api/#/?f=$.jstree.defaults.sort
 *   this function will receive 2 strings with the _id_s of the nodes to be sorted, not the nodes themselves.
 * @return 1 or -1. Will cause the nodes to be sorted alphanumerically using String.localeCompare(..). */
function action_sort(id_node1, id_node2)
{
    let node1 = $('#navtree').jstree(true).get_node(id_node1);
    let node2 = $('#navtree').jstree(true).get_node(id_node2);
    let code = node1.text.localeCompare(node2.text);
    return (code >= 0) ? 1 : -1;
}

问题在于,硬编码字符串#navtree显然仅适用于具有此id的树。

现在,他们在documentation中声明排序功能是在树的上下文中执行的。因此,我开始进行$(this)的实验,以在生长的树上获得复杂的非常大的内部数据结构。

进一步的实验试图找到拥有$('#'+id_node1)属性的role='tree'的第一父级。但是,在排序时仍无法以这种方式获得节点。

当然,我可能会为每个树生成或自动生成自定义排序功能。

但是真正的问题是:我的action_sort(id_node1, id_node2)函数是否有更简单的方法来利用它在“树的上下文”中运行来知道它在其中运行?或更重要的一点是:要获得一个我可以打电话给.get_node(node_id)的句柄?

1 个答案:

答案 0 :(得分:1)

如果您查看默认的排序处理程序$.jstree.defaults.sort函数,您会发现它在函数的上下文中使用了get_text函数。您可以在代码中为任何jsTree实例使用此功能

function (id_node1, id_node2) {
    return this.get_text(id_node1).localeCompare(this.get_text(id_node2));
}