如何在点击它时获取与YUI3树元素相关联的数据(TreeView构造函数中的“children”)

时间:2015-01-15 21:55:58

标签: javascript treeview yui alloy-ui

来自示例: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();

如果我将一些attrs添加到子数组对象,如:

    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"]

1 个答案:

答案 0 :(得分:0)

我认为您可能会将YUI中的Y.Tree类与AlloyUI中的Y.TreeView类混淆。您为iddata提供的说明来自Y.Tree使用的documentation for Y.Tree.Node from YUI

AlloyUI&#39; Y.TreeView课程使用的是Y.TreeNode个对象,而这些对象不具有您尝试用来存储自定义数据的data属性。看一下它的文档:http://alloyui.com/api/classes/A.TreeNode.html。要使用AlloyUI执行此操作,您需要添加一些自己的代码。例如,您可以扩展Y.TreeNode,将data属性添加到子类,然后使用它。或者,您可以将所需数据存储在每个Y.TreeNode实例的主节点中,您可以通过get('boundingBox')获取该数据,然后在其上使用setDatagetData。< / p>

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

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

然后你就可以通过:

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