2

我的 php 代码为 treeview 使用的 hierarchyDataSource 创建了一个分层的 json 数据集。

在这个 php 生成函数中,我将第一片叶子设置为 selected=true... 所以当树视图出现时,第一片叶子被自动选中。

问题在于,当用户单击任何叶子时,会触发一个事件 (onSelect),但不会因为在创建 UI 时出现树视图时自动选择第一个节点而触发该事件。

我怎样才能解决这个问题 ?

更新: 做了一个演示:http://jsbin.com/abapid/2/edit

4

2 回答 2

2

如果你想以编程方式触发一个select事件,你应该这样做:

$("#treeview").data("kendoTreeView").trigger("select");
于 2013-08-13T16:52:42.447 回答
1

For the benefits of others.... and thanks to OnaBai !... Here is the solution !

Kendo UI lacks many basic features other UI SDK always provide. One of them is an "onDisplay" kind of even that gets triggered once the widget gets painted. This would allow the application to react to specific case like in mine where the dataSource loaded a node containing a "selected = true" field.

The Kendo TreeView reacts by showing the node as selected but in most real world scenarios, the application would also need to react. That is why it would need to be called upon widget initialization to check if a node is selected and react accordingly.

The only hack we (OnaBai) found is to use the "DataBound" event as an "onDisplay" kind of event. The hic is that this event is fired each time a parent node as a child that got modified somehow. So it is called multiple times.

So here is the code to go around this limitation! http://jsbin.com/ejabul/4/edit (Note that you must click the "Run with JS" to simulate a page reload)

 $("#treeview").kendoTreeView({
    dataSource:data,
    dataTextField: "text",
    select: onSelect,
    dataBound: function (e) {
    var uid = undefined;
    var now = this.select();
    if (now) {
        var data = this.dataItem(now);
        uid = data.uid;
        if (uid && uid !== this.old_selected) {
            alert("Bingo !");
        }
        console.log("data", data.uid);
    }
    this.old_selected = uid;
    }
}); 

Explanation by OnaBai

  1. Store in uid the Unique ID of the selected item. This ID is introduced by Kendo UI for most node, items, … that it creates. Initially I set it to undefined (just in case there is nothing selected)
  2. "now" contains current selected node (if any).
  3. If there is an element selected (now !== undefined) then I get the data item for the selected node and then get the UID for this node.
  4. If there is a UID and if different than the UID of the previous selected node (that I store in a field that I just extended in the tree_view and I called old_selected) then I alert.
  5. finally I save the UID of the selected node for the next time.

Basically what I try is to control that I do not alert two consecutive times for the same node and for controlling it I save the UID of the selected node from one iteration to the next.

于 2013-08-14T16:48:54.223 回答