使用JSTree上下文菜单捕获新创建的节点

4
我正在尝试使用jstree的右键菜单来获取新创建节点的名称。我可以通过obj.text()捕获我正在添加新节点的父节点的名称,但我真正需要的是新创建节点的名称。
因此,某种方式需要在jstree上下文菜单中调用“onChange”事件,该事件会在用户在新创建节点上按Enter键时触发?
有什么想法吗?我已经附上了上下文菜单代码:
}).jstree({
        json_data: {
            data: RBSTreeModel,
            ajax: {
                type: "POST",
                data: function (n) {
                    return {
                        NodeID: n.attr("id").substring(4),
                        Level: n.attr("name").substring(7)
                    };
                },
                url: function (node) {
                    return "/Audit/GetRequirementsTreeStructure";
                },
                success: function (new_data) {
                    return new_data;
                }
            }
        },
        contextmenu: {
            items: function($node) {
                return {
                    createItem : {
                        "label" : "Create New Branch",
                        "action" : function(obj) { this.create(obj); alert(obj.text())},
                        "_class" : "class"
                    },
                    renameItem : {
                        "label" : "Rename Branch",
                        "action" : function(obj) { this.rename(obj);}
                    },
                    deleteItem : {
                        "label" : "Remove Branch",
                        "action" : function(obj) { this.remove(obj); }
                    }
                };
            }
        },
        plugins: ["themes", "json_data", "ui", "crrm", "contextmenu"]
    });
2个回答

6

您可以绑定到"create.jstree"事件,这将在节点创建后触发。在该事件的回调中,您将可以访问新创建的节点,如果选择,可以回滚/撤销创建节点操作。文档内容较少,但在演示页面上有一个示例。这是来自我的代码的另一个示例:

}).jstree({... You jstree setup code...})
        .bind("create.jstree", function(e, data) {
            // use your dev tools to examine the data object
            // It is packed with lots of useful info
            // data.rslt is your new node
            if (data.rslt.parent == -1) {
                alert("Can not create new root directory");
                // Rollback/delete the newly created node
                $.jstree.rollback(data.rlbk);
                return;
            }
            if (!FileNameIsValid(data.rslt.name)) {
                alert("Invalid file name");
                // Rollback/delete the newly created node
                $.jstree.rollback(data.rlbk);
                return;
            }
            .. Your code etc...
        })

谢谢,这正是我想要的。jstree文档有待改进的地方。 - winkbrace
@Bojin Li,最新版本的jstree中似乎缺少了rollback() api。你能提供一个回滚的替代方法吗? - Dattatreya Kugve

3
根据Bojin Li的回答,最新版本的jsTree使用事件"create_node"代替"create":
}).jstree({...你的jsTree设置代码...})
      .bind("create_node.jstree", function(e, data) {
        ...
       });


很奇怪,当我尝试绑定到create_node.jstree事件时,它在新节点实际创建之前就触发了,所以我得到的文本总是“New Node”,而不是用户想要给它的任何名称...你知道如何在新节点创建后捕获它吗? - taki Martillo
我认为你需要使用rename_node.jstree,就像这里提到的那样。 - Dattatreya Kugve

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接