如何在单击时获取与 YUI3 树元素关联的数据(TreeView 构造函数中的 "children")

How to get data ("children" in TreeView constructor) associated with YUI3 tree element on clicking by it

来自示例:enter link description here

// Create an array object for the tree root and child nodes
var children = [
  {
    children: [
      {
        label: 'File X'
      },
      {
        label: 'File Y'
      }
    ],
    expanded: true,
    label: 'Root'
  }
];

// Create a TreeView Component
tree = new Y.TreeView(
  {
    boundingBox: '#myTreeView',
    children: children
  }
).render();

如果我向子数组对象添加一些属性,例如:

    children: [
              {
                label: 'File X',
                internalId: 24342234,
                customAttr: 'unicid',
              }
            ]

  var tree.on('click',function(e){
     tree.get('lastSelected');
  });

我无法在树渲染并单击此树节点后获取它们。 所有节点都具有以下内置属性:

data Object 与节点相关的任意可序列化数据。当节点序列化为 JSON.

时,使用此 属性 存储应伴随该节点的任何数据

id String 节点的唯一 ID。如果在创建节点时不指定自定义id,则会自动生成一个。

但它对我不起作用..

 console.log(tree.get('lastSelected').get('label'));
 [gives "File X"]
 console.log(tree.get('lastSelected').get('customAttr'));
 [gives "undefined"]

我认为您可能混淆了 YUI 的 Y.Tree class 和 AlloyUI 的 Y.TreeView class。您为 iddata 提供的描述来自 documentation for Y.Tree.Node from YUI,它被 Y.Tree 使用。

AlloyUI 的 Y.TreeView class 使用 Y.TreeNode 对象,它没有您试图用来存储自定义数据的 data 属性。查看其文档:http://alloyui.com/api/classes/A.TreeNode.html。要使用 AlloyUI 执行此操作,您需要添加一些您自己的代码。例如,您可以扩展 Y.TreeNode,将 data 属性添加到 subclass,然后改用它。或者你可以把你需要的数据存储在每个Y.TreeNode实例的主节点中,你可以通过get('boundingBox')获取,然后在上面使用setDatagetData

即使 Y.TreeNode 具有此 data 属性,您也需要更改代码以在 data 键中添加您需要的自定义数据,而不是将它们加在一起与其他属性。例如:

children: [
  {
    label: 'File X',
    data: {
      internalId: 24342234,
      customAttr: 'unicid'
    }
   }
]

那你就可以通过了:

console.log(tree.get('lastSelected').get('data').customAttr);