You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用treeSortable时两个排序完成事件同时触发问题排查

问题原因与解决方案

问题根源

treeSortable的onSortCompleted方法是把回调函数绑定到全局document对象的sortcompleted事件上,而非与当前实例对应的树形结构绑定。因此不管哪个树触发排序完成事件,所有绑定在document上的回调都会被执行,导致两个日志同时输出。

修复方案

有两种可行的解决方式:

方式1:在回调里判断触发事件的树

通过UI元素的父级关系,判断当前触发排序的是哪个树,再执行对应逻辑:

// 修改sortable1的回调
sortable1.onSortCompleted(function(event, ui) {
    if ($(ui.item).closest('#tree1').length) {
        console.log('continents');
    }
});

// 修改sortable2的回调
sortable2.onSortCompleted(function(event, ui) {
    if ($(ui.item).closest('#tree2').length) {
        console.log('States');
    }
});

方式2:把回调配置到实例的options中(推荐)

treeSortable支持将onSortCompleted作为options的属性直接设置,这样回调会与当前实例绑定,仅响应对应树的排序事件。注意要在调用run()前配置好options:

// 配置sortable1的options时加入回调
sortable1.options = {
    depth: 30,
    treeSelector: '#tree1',
    branchSelector: '.tree-branch',
    branchPathSelector: '.branch-path',
    dragHandlerSelector: '.branch-drag-handler',
    placeholderName: 'sortable-placeholder',
    childrenBusSelector: '.children-bus',
    levelPrefix: 'branch-level',
    maxLevel: 10,
    dataAttributes: {
        id: 'id',
        parent: 'parent',
        level: 'level'
    },
    // 添加排序完成回调
    onSortCompleted: function(event, ui) {
        console.log('continents');
    }
}
sortable1.run();

// 配置sortable2的options时加入回调
sortable2.options = {
    depth: 30,
    treeSelector: '#tree2',
    branchSelector: '.tree-branch',
    branchPathSelector: '.branch-path',
    dragHandlerSelector: '.branch-drag-handler',
    placeholderName: 'sortable-placeholder',
    childrenBusSelector: '.children-bus',
    levelPrefix: 'branch-level',
    maxLevel: 10,
    dataAttributes: {
        id: 'id',
        parent: 'parent',
        level: 'level'
    },
    // 添加排序完成回调
    onSortCompleted: function(event, ui) {
        console.log('States');
    }
}
sortable2.run();

注意事项

如果使用方式2,一定要确保在调用run()方法前就完成包含回调的options配置,否则回调不会生效。这种方式能避免全局事件冲突,是更规范的用法。


内容的提问来源于stack exchange,提问作者Deen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 15:05:35