Search code examples
javascripttreeviewyuialloy-ui

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


from example: 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();

if I add some attrs to children array objects like:

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

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

I can't get them after tree rendering and clicking on this tree node. All nodes have the following built-in properties:

data Object Arbitrary serializable data related to the node. Use this property to store any data that should accompany a node when that node is serialized to JSON.

id String Unique id for the node. If you don't specify a custom id when creating a node, one will be generated automatically.

but it does not work for me..

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

Solution

  • I think you may be confusing the Y.Tree class from YUI with the Y.TreeView class from AlloyUI. The descriptions you gave for id and data come from the documentation for Y.Tree.Node from YUI, which is used by Y.Tree.

    AlloyUI's Y.TreeView class uses Y.TreeNode objects instead, which don't have the data attribute you're trying to use to store custom data. Take a look at its documentation: http://alloyui.com/api/classes/A.TreeNode.html. To do this with AlloyUI you'll need to add some code of your own. You could extend Y.TreeNode for example, adding the data attribute to the subclass, and use it instead. Or you can store the data you need in the main node of each Y.TreeNode instance, which you can get via get('boundingBox'), and then use setData and getData on it.

    Even if Y.TreeNode had this data attribute though, you'd need to change your code to add the custom data you need inside the data key instead of adding them together with the other attributes. For example:

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

    Then you'd be able to get it through:

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