Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
1923
CSOM - Find by data key
posted

I wasn't able to find a function in the help document (or exploring the dom) to find a node by its datakey in the clientside code. I'm basically after the Find code behind function which accepts datakey to find a node.

Otherwise i guess it's a loop through all the nodes and compare...i'll post the result unless someone beats me to it (thanks heaps if you do!!)

Parents
No Data
Reply
  • 1923
    Verified Answer
    posted

    Done. If anybody can improve it, please post your changes...ig, can you include this in your next release :p

    Note: requires that you actually set a unique datakey in your code...can easily be changed to look at tags...just use getTag() instead of getDataKey() (further to that, any property of a node!)...and perhaps then add them to an array or something...

    function igtree_getNodeByDataKey(treeId, dataKey) {
        ///<summary>searches a tree and returns a node based on dataKey. Remember to enable DataKeyOnClient in control.</summary>
        ///<param name="treeId">the unique ID of the tree to search</param>
        ///<param name="dataKey">the dataKey of the node to find</param>
        ///<returns>webtree node with the passed in dataKey</returns>
       
        // a few simple checks...
        var tre = igtree_getTreeById(treeId);
        if (!tre) return;
        var nodes = tre.getNodes();
        if (nodes.length === 0) return;
       
        // new object
        var searcher = {};
        // store what we are looking for
        searcher.target = dataKey;
        // compare function
        searcher.compare = function(node) {
            if (node.getDataKey() == this.target) return node;
        }
        // recursive loop function
        searcher.iterate = function(node) {
            if (this.compare(node)) return node;
            if (node.hasChildren()) {
                var children = node.getChildNodes();
                for (var cid in children) {
                    //if (this.compare(children[cid])) return children[cid];
                    var result = this.iterate(children[cid]);
                    if (result) return result;
                }
            }
        }

        // start the whole process
        // -- searching
        for (var id in nodes) {
            var result = searcher.iterate(nodes[id]);
            if (result) return result;
        }
       
        // nothing found...
        return;
    }

Children
No Data