CocosCreator 源码​cocos2d/core/utils/find.js详解


/**
 * Finds a node by hierarchy path, the path is case-sensitive.
 * It will traverse the hierarchy by splitting the path using '/' character.
 * This function will still returns the node even if it is inactive.
 * It is recommended to not use this function every frame instead cache the result at startup.
 *
 * @method find
 * @static
 * @param {String} path
 * @param {Node} [referenceNode]
 * @return {Node|null} the node or null if not found
 */
/**
 * 按层次结构路径查找节点,路径区分大小写。
 * 它将通过使用“/”字符分割路径来遍历层次结构。
 * 即使该节点处于非活动状态,该函数仍将返回该节点。
 * 建议不要每帧都使用此函数,而是在启动时缓存结果。
 *
 * @方法查找
 * @静止的
 * @param {String} 路径
 * @param {Node} [参考节点]
 * @return {Node|null} 节点,如果没有找到则返回 null
 */
cc.find = module.exports = function (path, referenceNode) {
    if (path == null) {
        cc.errorID(3814);//Argument must be non-nil
        return null;
    }
    if (!referenceNode) {
        var scene = cc.director.getScene();
        if (!scene) {
            if (CC_DEV) {
                cc.warnID(5601);
            }
            return null;
        }
        else if (CC_DEV && !scene.isValid) {
            cc.warnID(5602);
            return null;
        }
        referenceNode = scene;
    }
    else if (CC_DEV && !referenceNode.isValid) {
        /* node已经被销毁 */
        cc.warnID(5603);
        return null;
    }

    var match = referenceNode;
    /* 当字符串第一个字符为/的时候,确认index的开启为0 还是1 */
    var startIndex = (path[0] !== '/') ? 0 : 1; // skip first '/'
    var nameList = path.split('/');

    // parse path
    for (var n = startIndex; n < nameList.length; n++) {
        var name = nameList[n];//路径名称数组
        var children = match._children;//match的子节点数组
        match = null;
        for (var t = 0, len = children.length; t < len; ++t) {
            var subChild = children[t];
            if (subChild.name === name) {//路径名称 和对应的child的名称匹配,匹配上以后break
                match = subChild;
                break;
            }
        }
        if (!match) {//只要有一层路径和名称不匹配,就直接return出去了
            return null;
        }
    }
/* 当所有的路径名称和 node节点名称,最终都匹配的话,则返回match的node节点 */
    return match;
};

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值