jstree记得打开/关闭的树节点

时间:2013-04-05 20:14:02

标签: jquery jstree

我正在使用jstree来显示/管理类别树。我正在使用Ajax调用获取树,并返回以下响应:

0: {id:35, name:amrs trade, parent_id:null}
1: {id:36, name:trips, parent_id:35}
2: {id:37, name:tribute, parent_id:null}
3: {id:38, name:music, parent_id:null}
4: {id:39, name:recordings, parent_id:38}
5: {id:40, name:live shows, parent_id:38}
6: {id:41, name:others, parent_id:null}
7: {id:42, name:investments, parent_id:null}
8: {id:43, name:gold & silver, parent_id:42}
9: {id:44, name:debentures, parent_id:42}
10: {id:46, name:production, parent_id:35}
11: {id:54, name:real estate, parent_id:42}

我正在使用json_data选项呈现jstree:

$("#incomeCategoryTree").jstree({
    "json_data" : {
        "data" : income,
        "progressive_render" : true
    },
    "plugins" : [ "themes", "json_data" ]
})
.bind("open_node.jstree close_node.jstree", function (e) {
    console.log(e);
});

我想记住用户所做的每个操作(打开或关闭任何树节点),因此我绑定了open_nodeclose_node操作。我遇到的问题是该事件没有关于刚刚点击的节点的信息:

.Event {type: "open_node", timeStamp: 1365192438814, jQuery183029903660411946476: true, isTrigger: true, exclusive: undefined…}

currentTarget: div#incomeCategoryTree.jstree jstree-0 jstree-default jstree-focused
data: null
delegateTarget: div#incomeCategoryTree.jstree jstree-0 jstree-default jstree-focused
exclusive: undefined
handleObj: Object
isTrigger: true
jQuery183029903660411946476: true
namespace: "jstree"
namespace_re: /(^|\.)jstree(\.|$)/
result: undefined
target: div#incomeCategoryTree.jstree jstree-0 jstree-default jstree-focused
timeStamp: 1365192438814
type: "open_node"
__proto__: Object

我想我错过了,但是jstree docs非常糟糕,并且大多数选项甚至没有被提及......

1 个答案:

答案 0 :(得分:2)

我设法做了以下事情:

$("#incomeCategoryTree").jstree({
    "json_data" : {
        "data" : income,
        "progressive_render" : true
    },
    "plugins" : [ "themes", "json_data" ]
})
.bind("open_node.jstree close_node.jstree", function (event, data) {
    var state = event.type == "open_node" ? "open" : "closed";
    IncomeCategoryControl.setState(data.rslt.obj.attr("id"), state)
});

这是管理树数据的对象

var IncomeCategoryControl = {
    data: null,
    fetchData: function() {
        $.ajax({
            type: "GET",
            dataType: "json",
            context: this,
            async: false,
            url: "../php/client/json.php",
            data: {
                type: "incomeCategories"
            }
        }).done(function(response) {
            this.data = response;
        });
    },
    getData: function() {
        if (this.data == null) {
            this.fetchData();
        }
        return this.data;
    },
    setState: function(id, value) {
        var found = $(this.getData()).map(function() {
            return (this.id == id) ? this : null;
        });
        if (found.length) {
            found[0].state = value;
            return true;
        } else {
            return false;
        }
    }
};