jquery-treegrid 控件封装

jquery-treegrid 控件封装

月光魔力鸭

2018-09-03 08:31 阅读 744 喜欢 0 treegrid封装 treegrid控件

项目中需要使用treegrid,找了下easyuiext都有,但是项目用的框架是 byyui,如果为了treegrid 就把这些都加载的话,感觉不太合算。找了大家常用的基于jquerytreegrid. http://maxazan.github.io/jquery-treegrid/

但是这个是基于DOM进行CSS控制渲染的,项目中使用必然是从数据库加载数据再渲染了。于是从这个基础上进行扩展,增加远程数据加载、点击选中行、复选单选、异步加载子节点等。

直接上代码

/*
 * jQuery treegrid Plugin 0.3.0
 * https://github.com/maxazan/jquery-treegrid
 *
 * Copyright 2013, Pomazan Max
 * Licensed under the MIT licenses.
 */

 //暴露接口

byy.define(['jquery','cookie'],function( exports ){

    (function($) {
        var nodeCount = 0;
        //从数据中获取跟结点
        var getRootNodesFromData = function (data,isTreedData,parentCol,sortCol,rootValue) {
            var result = [];
            $.each(data, function (index, item) {
                if (isTreedData || !item[parentCol] || item[parentCol] == rootValue) {
                    result.push(item);
                }
            });
            if (sortCol) {
                result.sort(function (a, b) {
                    return a[sortCol] - b[sortCol];
                });
            }
            return result;

        }
        //从数据中获取子节点
        var getListChildNodesFromData = function (data, parentNode,idCol,parentCol,sortCol) {
            var unsort = [];
            $.each(data, function (i, item) {
                if (item[parentCol] == parentNode[idCol]) {
                    unsort.push(item);
                }
            });
            if (unsort == null || unsort.length < 1)
                return;

            if (sortCol) {
                unsort.sort(function (a, b) {
                    return a[sortCol] - b[sortCol];
                });
            }
            return unsort;
        }
        var getTreeChildNodesFromdata = function (parentNode,childCol,sortCol) {
            if (childCol) {
                var childNodes = parentNode[childCol];
                if (sortCol)
                    childNodes.sort(function (a, b) {
                        return a[sortCol] - b[sortCol];
                    });
                return childNodes;
            }
            return null;
        }


        var methods = {
            /**
             * Initialize tree
             *
             * @param {Object} options
             * @returns {Object[]}
             */
            initTree: function(options) {
                var settings = $.extend({}, this.treegrid.defaults, options);
                return this.each(function() {
                    var $this = $(this);
                    $this.treegrid('setTreeContainer', $(this));
                    $this.treegrid('setSettings', settings);
                    //1.加载数据
                    $this.treegrid('loadData',settings);


                    // settings.getRootNodes.apply(this, [$(this)]).treegrid('initNode', settings);
                    // $this.treegrid('getRootNodes').treegrid('render');
                    //默认展开状态
                    if (!settings.expandAll) {
                        $this.treegrid('collapseAll');
                    }
                });
            },
            //tr 加载子节点
            loadChildNodes : function(){
                var $this = $(this);
                var trItem = $this.data('obj');
                
                var beforeFn = $this.treegrid('getSetting','onBefore');
                if(typeof beforeFn === 'function' && !beforeFn.apply($this)){
                    //如果返回false,则停止继续加载
                    return;
                }

                var url = $this.treegrid('getSetting','url'),
                    type = $this.treegrid('getSetting','type'),
                    data = $this.treegrid('getSetting','ajaxParams'),
                    parentColumn = $this.treegrid('getSetting','parentColumn'),
                    idColumn = $this.treegrid('getSetting','idColumn');
                data[parentColumn] = trItem[idColumn];
                $.ajax({
                    url : url,
                    type : type,
                    data : data,
                    success : function(res){
                        var data = res.rows || res.list || res;
                        $this.treegrid('renderChild',data);
                        //渲染完毕后,重新加载事件等
                        var $tree = $this.treegrid('getTableByTr');
                        var settings = $tree.data('settings');
                        settings.getRootNodes.apply(this, [$tree]).treegrid('initNode', settings);
                        $tree.treegrid('getRootNodes').treegrid('render');
                        //当前节点展开
                        var expander = $this.treegrid('getSetting', 'getExpander').apply($this);
                        if(expander){
                            expander.removeClass($this.treegrid('getSetting', 'expanderCollapsedClass'));
                            expander.addClass($this.treegrid('getSetting', 'expanderExpandedClass'));
                        }
                        trItem['sync'] = true;
                        $(this).data('obj',trItem);
                        byy.initUI();
                        //渲染分页数据 
                        //UNDO
                        //调用加载成功函数
                        if (typeof($this.treegrid('getSetting', 'onSuccess')) === "function") {
                            $this.treegrid('getSetting', 'onSuccess').apply($this,[res]);
                        }
                        
                    },
                    error : function(req,txt){
                        if (typeof($this.treegrid('getSetting', 'onError')) === "function") {
                            $this.treegrid('getSetting', 'onError').apply($this,[req,txt]);
                        }
                    }
                });
            },
            //加载子级节点
            renderChild : function( data ){
                var $this = $(this);
                var isTreedData = $this.treegrid('getSetting', 'treedData');
                var parentCol = $this.treegrid('getSetting', 'parentColumn');
                var sortCol = $this.treegrid('getSetting', 'sortColumn');
                var cols = $this.treegrid('getSetting', 'columns');
                var checkOrRadio = $this.treegrid('getSetting','checkOrRadio');
                var idCol = $this.treegrid('getSetting', 'idColumn');
                var treeColumn = $this.treegrid('getSetting','treeColumn');
                var rootValue = $this.treegrid('getSetting','rootValue');
                var rootNodes = getRootNodesFromData(data, isTreedData, parentCol, sortCol,rootValue);
                var parentIndex = $this.treegrid('getNodeId');
                var $beforeTr = $this.next('tr'),$tbody = $this.treegrid('getTableByTr').find('tbody');
                if (rootNodes && rootNodes.length > 0) {
                    $.each(rootNodes, function (i, item) {
                        var tr = $('<tr></tr>');
                        tr.data('obj',item);
                        tr.addClass('treegrid-' + (++nodeCount));
                        tr.addClass('treegrid-parent-' + parentIndex);
                        $.each(cols, function (index, column) {
                            var td = $('<td></td>');
                            if(index == treeColumn){
                                if(checkOrRadio !== false){
                                    td.append(( checkOrRadio == 'check' ? '<span class="list-check-span"><input type="checkbox" title=" " byy-skin="primary" name="treegrid-checkbox" value="'+(item[idCol])+'" class="byy-form-checkbox"/></span>'+item[column.field] : '<span class="list-check-span"><input type="radio" name="treegrid-radio" value="'+(item[idCol])+'" class="byy-form-radio" title=" "/></span>'+item[column.field])+'');
                                }else{
                                    td.text(item[column.field]);        
                                }
                            }else{
                                td.text(item[column.field]);        
                            }
                            tr.append(td);
                        });
                        //看有没有下一个,body
                        $beforeTr.length >0 ? $beforeTr.before(tr) : $tbody.append(tr);
                        $this.treegrid('renderChildList', data, item, nodeCount, cols, idCol, parentCol, sortCol,checkOrRadio,treeColumn,tr);
                    });
                }
                byy.initUI();
                return $this;
            },
            getTableByTr : function(){
                return $(this)[0].nodeName == 'TABLE' ? $(this) : $(this).parents('table');
            },
            renderChildList : function(data, parentData, parentIndex, columns, idColumn, parentColumn, sortColumn,checkOrRadio,treeColumn,ptr){
                var $this = $(this);
                var $beforeTr = ptr.next('tr'),$tbody = $this.treegrid('getTableByTr').find('tbody');
                var nodes = getListChildNodesFromData(data, parentData, idColumn, parentColumn, sortColumn);
                if (nodes && nodes.length > 0) {
                    $.each(nodes, function (i, item) {
                        var tr = $('<tr></tr>');
                        tr.data('obj',item);
                        var nowParentIndex = ++nodeCount;
                        tr.addClass('treegrid-' + nowParentIndex);
                        tr.addClass('treegrid-parent-' + parentIndex);
                        $.each(columns, function (index, column) {
                            var td = $('<td></td>');
                            if(index == treeColumn){
                                if(checkOrRadio !== false){
                                    td.append(''+( checkOrRadio == 'check' ? '<span class="list-check-span"><input type="checkbox" byy-skin="primary" title=" " name="treegrid-checkbox" value="'+(item[idColumn])+'" class="byy-form-checkbox"/></span>'+item[column.field] : '<span class="list-check-span"><input type="radio" name="treegrid-radio" value="'+(item[idColumn])+'" class="byy-form-radio" title=" " /></span> '+item[column.field])+'');
                                }else{
                                    td.text(item[column.field]);        
                                }
                            }else{
                                td.text(item[column.field]);        
                            }
                            tr.append(td);
                        });
                        //看有没有下一个,body
                        $beforeTr.length >0 ? $beforeTr.before(tr) : $tbody.append(tr);
                        $this.treegrid('renderChildList', data, item, nowParentIndex, columns, idColumn, parentColumn, sortColumn,checkOrRadio,treeColumn,tr);
                    });
                }
            },
            loadData : function(settings){
                var $this = $(this);
                var beforeFn = $this.treegrid('getSetting','onBefore');
                if(typeof beforeFn === 'function' && !beforeFn.apply($this)){
                    //如果返回false,则停止继续加载
                    return;
                }
                $.ajax({
                    url : settings.url,
                    type : settings.type,
                    data : settings.ajaxParams,
                    dataType : 'JSON',
                    success : function( res ){
                        res = byy.json(res);
                        var data = res.rows || res.list || res;
                        $this.treegrid('renderTable',data);
                        settings.getRootNodes.apply(this, [$this]).treegrid('initNode', settings);
                        $this.treegrid('getRootNodes').treegrid('render');
                        byy.initUI();
                        //渲染分页数据 
                        //UNDO
                        //调用加载成功函数
                        if (typeof($this.treegrid('getSetting', 'onSuccess')) === "function") {
                            $this.treegrid('getSetting', 'onSuccess').apply($this,[res]);
                        }
                    },
                    error : function(req,txt){
                        if (typeof($this.treegrid('getSetting', 'onError')) === "function") {
                            $this.treegrid('getSetting', 'onError').apply($this,[req,txt]);
                        }
                    }
                });
            },
            renderTable : function(data){
                var $this = $(this);
                if($this.treegrid('getSetting','striped')){
                    $this.attr('byy-even','even');
                }
                var skin = ['','row','line','nob'];
                var border = $this.treegrid('getSetting','border');
                $this.attr('byy-skin',skin[byy.isNull(border) ? 0 : (border > 3 ? 0 : border)]);
                $this.html('');
                $this.treegrid('renderHead');
                $this.treegrid('renderBody',data);
                $this.treegrid('initSelfEvents');
                return $this;
            },
            //添加一些自定义事件
            initSelfEvents : function(){

                $this = $(this);
                $this.off('click','tr').on('click','tr',function(){
                    var $tr = $(this);
                    $this.treegrid('clickRow',$tr);
                });
                return $this;
            },
            //选中行,仅限当前页面
            clickRow : function( $tr ){
                var $this = $(this);
                if($tr.hasClass('treegridExt-header')){
                    return;
                }
                var single = $this.treegrid('getSetting','single');
                var checkOrRadio = $this.treegrid('getSetting','checkOrRadio');//单选还是复选
                var hasSel = $tr.hasClass('selected');
                if(single === true){//单选,则取消其他选择
                    $this.find('tr.selected').removeClass('selected');
                    $this.find('[name="treegrid-checkbox"]').prop('checked',false);
                }
                hasSel ? $tr.removeClass('selected') : $tr.addClass('selected');
                $tr.find('[name="treegrid-checkbox"],[name="treegrid-radio"]').prop('checked',!hasSel);
                byy($this).initUI();
                //callback
                if(typeof $this.treegrid('getSetting','onClick') === 'function'){
                    var item = $tr.data('obj');
                    $this.treegrid('getSetting','onClick').apply($this,[item]);
                }
                return $this;
            },
            renderHead: function () {
                var $this = $(this);
                //debugger;
                var thead = $('<thead></thead>')
                var thr = $('<tr></tr>');
                thr.addClass('treegridExt-header');
                var checkOrRadio = $this.treegrid('getSetting','checkOrRadio');
                var treeColumn = $this.treegrid('getSetting','treeColumn');
                $.each($this.treegrid('getSetting', 'columns'), function (i, item) {
                    var th = $('<td></td>');
                    if(i == treeColumn){
                        if(checkOrRadio !== false && checkOrRadio == 'check'){
                            th.append('<span class="list-check-span"><input type="checkbox" title=" " byy-skin="primary" value="" name="checkAll" class="byy-form-checkbox"/></span>'+item.title);
                        }else{
                            th.text(item.title);
                        }
                    }else{
                        th.text(item.title);
                    }
                    thr.append(th);
                });
                thr.appendTo(thead);
                return $this.append(thead);
            },
            renderBody: function (data) {
                var $this = $(this);
                var tbody = $('<tbody></tbody>');
                var isTreedData = $this.treegrid('getSetting', 'treedData');
                var parentCol = $this.treegrid('getSetting', 'parentColumn');
                var sortCol = $this.treegrid('getSetting', 'sortColumn');
                var cols = $this.treegrid('getSetting', 'columns');
                var checkOrRadio = $this.treegrid('getSetting','checkOrRadio');
                var idCol = $this.treegrid('getSetting', 'idColumn');
                var treeColumn = $this.treegrid('getSetting','treeColumn');
                var rootValue = $this.treegrid('getSetting','rootValue');
                var rootNodes = getRootNodesFromData(data, isTreedData, parentCol, sortCol,rootValue);
                if (rootNodes && rootNodes.length > 0) {
                    $.each(rootNodes, function (i, item) {
                        var tr = $('<tr></tr>');
                        tr.data('obj',item);
                        tr.addClass('treegrid-' + (++nodeCount));
                        $.each(cols, function (index, column) {
                            var td = $('<td></td>');
                            if(index == treeColumn){
                                if(checkOrRadio !== false){
                                    td.append(( checkOrRadio == 'check' ? '<span class="list-check-span"><input type="checkbox" title=" " byy-skin="primary" name="treegrid-checkbox" value="'+(item[idCol])+'" class="byy-form-checkbox"/></span>'+item[column.field] : '<span class="list-check-span"><input type="radio" name="treegrid-radio" value="'+(item[idCol])+'" class="byy-form-radio" title=" "/></span>'+item[column.field])+'');
                                }else{
                                    td.text(item[column.field]);        
                                }
                            }else{
                                td.text(item[column.field]);        
                            }
                            tr.append(td);
                        });
                        
                        tbody.append(tr);
                        $this.treegrid('renderListDataTr', data, item, nodeCount, cols, idCol, parentCol, sortCol, tbody,checkOrRadio,treeColumn);
                    });
                }
                byy.initUI();
                return $this.append(tbody);
            },
            //获得当前选中的行
            getSelectedNodes : function(){
                var $this = $(this);
                var trs = $this.find('tbody tr.selected');
                var datas = [];
                if(trs.length>0){
                    trs.each(function( i ){
                        datas.push($(this).data('obj'));
                    });
                }
                return datas;
            },
            renderListDataTr: function (data, parentData, parentIndex, columns, idColumn, parentColumn, sortColumn, tbody,checkOrRadio,treeColumn) {
                var $this = $(this);

                var nodes = getListChildNodesFromData(data, parentData, idColumn, parentColumn, sortColumn);
                if (nodes && nodes.length > 0) {
                    $.each(nodes, function (i, item) {
                        var tr = $('<tr></tr>');
                        tr.data('obj',item);
                        var nowParentIndex = ++nodeCount;
                        tr.addClass('treegrid-' + nowParentIndex);
                        tr.addClass('treegrid-parent-' + parentIndex);
                        $.each(columns, function (index, column) {
                            var td = $('<td></td>');
                            if(index == treeColumn){
                                if(checkOrRadio !== false){
                                    td.append(''+( checkOrRadio == 'check' ? '<span class="list-check-span"><input type="checkbox" byy-skin="primary" title=" " name="treegrid-checkbox" value="'+(item[idColumn])+'" class="byy-form-checkbox"/></span>'+item[column.field] : '<span class="list-check-span"><input type="radio" name="treegrid-radio" value="'+(item[idColumn])+'" class="byy-form-radio" title=" " /></span> '+item[column.field])+'');
                                }else{
                                    td.text(item[column.field]);        
                                }
                            }else{
                                td.text(item[column.field]);        
                            }
                            tr.append(td);
                        });
                        tbody.append(tr);
                        $this.treegrid('renderListDataTr', data, item, nowParentIndex, columns, idColumn, parentColumn, sortColumn, tbody,checkOrRadio,treeColumn);
                    });
                }
            },
            /**
             * Initialize node
             *
             * @param {Object} settings
             * @returns {Object[]}
             */
            initNode: function(settings) {
                return this.each(function() {
                    var $this = $(this);
                    $this.treegrid('setTreeContainer', settings.getTreeGridContainer.apply(this));
                    $this.treegrid('getChildNodes').treegrid('initNode', settings);
                    $this.treegrid('initExpander').treegrid('initIndent').treegrid('initEvents').treegrid('initState').treegrid('initChangeEvent').treegrid("initSettingsEvents");
                });
            },
            initChangeEvent: function() {
                var $this = $(this);
                //Save state on change
                $this.on("change", function() {
                    var $this = $(this);
                    $this.treegrid('render');
                    if ($this.treegrid('getSetting', 'saveState')) {
                        $this.treegrid('saveState');
                    }
                });
                return $this;
            },
            /**
             * Initialize node events
             *
             * @returns {Node}
             */
            initEvents: function() {
                var $this = $(this);
                //Default behavior on collapse
                $this.on("collapse", function() {
                    var $this = $(this);
                    $this.removeClass('treegrid-expanded');
                    $this.addClass('treegrid-collapsed');
                });
                //Default behavior on expand
                $this.on("expand", function() {
                    var $this = $(this);
                    $this.removeClass('treegrid-collapsed');
                    $this.addClass('treegrid-expanded');
                });

                return $this;
            },
            /**
             * Initialize events from settings
             *
             * @returns {Node}
             */
            initSettingsEvents: function() {
                var $this = $(this);
                //Save state on change
                $this.on("change", function() {
                    var $this = $(this);
                    if (typeof($this.treegrid('getSetting', 'onChange')) === "function") {
                        $this.treegrid('getSetting', 'onChange').apply($this);
                    }
                });
                //Default behavior on collapse
                $this.on("collapse", function() {
                    var $this = $(this);
                    if (typeof($this.treegrid('getSetting', 'onCollapse')) === "function") {
                        $this.treegrid('getSetting', 'onCollapse').apply($this);
                    }
                });
                //Default behavior on expand
                $this.on("expand", function() {
                    var $this = $(this);
                    if (typeof($this.treegrid('getSetting', 'onExpand')) === "function") {
                        $this.treegrid('getSetting', 'onExpand').apply($this);
                    }

                });

                return $this;
            },
            /**
             * Initialize expander for node
             *
             * @returns {Node}
             */
            initExpander: function() {
                var $this = $(this);
                var cell = $this.find('td').get($this.treegrid('getSetting', 'treeColumn'));
                var tpl = $this.treegrid('getSetting', 'expanderTemplate');
                var expander = $this.treegrid('getSetting', 'getExpander').apply(this);
                if (expander) {
                    expander.remove();
                }
                $(tpl).prependTo(cell).click(function() {
                    $($(this).closest('tr')).treegrid('toggle');
                });
                return $this;
            },
            /**
             * Initialize indent for node
             *
             * @returns {Node}
             */
            initIndent: function() {
                var $this = $(this);
                $this.find('.treegrid-indent').remove();
                var tpl = $this.treegrid('getSetting', 'indentTemplate');
                var expander = $this.find('.treegrid-expander');
                var depth = $this.treegrid('getDepth');
                for (var i = 0; i < depth; i++) {
                    $(tpl).insertBefore(expander);
                }
                return $this;
            },
            /**
             * Initialise state of node
             *
             * @returns {Node}
             */
            initState: function() {
                var $this = $(this);
                if ($this.treegrid('getSetting', 'saveState') && !$this.treegrid('isFirstInit')) {
                    $this.treegrid('restoreState');
                } else {
                    if ($this.treegrid('getSetting', 'initialState') === "expanded") {
                        $this.treegrid('expand');
                    } else {
                        $this.treegrid('collapse');
                    }
                }
                return $this;
            },
            /**
             * Return true if this tree was never been initialised
             *
             * @returns {Boolean}
             */
            isFirstInit: function() {
                var tree = $(this).treegrid('getTreeContainer');
                if (tree.data('first_init') === undefined) {
                    tree.data('first_init', $.cookie(tree.treegrid('getSetting', 'saveStateName')) === undefined);
                }
                return tree.data('first_init');
            },
            /**
             * Save state of current node
             *
             * @returns {Node}
             */
            saveState: function() {
                var $this = $(this);
                if ($this.treegrid('getSetting', 'saveStateMethod') === 'cookie') {

                    var stateArrayString = $.cookie($this.treegrid('getSetting', 'saveStateName')) || '';
                    var stateArray = (stateArrayString === '' ? [] : stateArrayString.split(','));
                    var nodeId = $this.treegrid('getNodeId');

                    if ($this.treegrid('isExpanded')) {
                        if ($.inArray(nodeId, stateArray) === -1) {
                            stateArray.push(nodeId);
                        }
                    } else if ($this.treegrid('isCollapsed')) {
                        if ($.inArray(nodeId, stateArray) !== -1) {
                            stateArray.splice($.inArray(nodeId, stateArray), 1);
                        }
                    }
                    $.cookie($this.treegrid('getSetting', 'saveStateName'), stateArray.join(','));
                }
                return $this;
            },
            /**
             * Restore state of current node.
             *
             * @returns {Node}
             */
            restoreState: function() {
                var $this = $(this);
                if ($this.treegrid('getSetting', 'saveStateMethod') === 'cookie') {
                    var stateArray = $.cookie($this.treegrid('getSetting', 'saveStateName')).split(',');
                    if ($.inArray($this.treegrid('getNodeId'), stateArray) !== -1) {
                        $this.treegrid('expand');
                    } else {
                        $this.treegrid('collapse');
                    }

                }
                return $this;
            },
            /**
             * Method return setting by name
             *
             * @param {type} name
             * @returns {unresolved}
             */
            getSetting: function(name) {
                if (!$(this).treegrid('getTreeContainer')) {
                    return null;
                }
                return $(this).treegrid('getTreeContainer').data('settings')[name];
            },
            /**
             * Add new settings
             *
             * @param {Object} settings
             */
            setSettings: function(settings) {
                $(this).treegrid('getTreeContainer').data('settings', settings);
            },
            /**
             * Return tree container
             *
             * @returns {HtmlElement}
             */
            getTreeContainer: function() {
                return $(this).data('treegrid');
            },
            /**
             * Set tree container
             *
             * @param {HtmlE;ement} container
             */
            setTreeContainer: function(container) {
                return $(this).data('treegrid', container);
            },
            /**
             * Method return all root nodes of tree.
             *
             * Start init all child nodes from it.
             *
             * @returns {Array}
             */
            getRootNodes: function() {
                return $(this).treegrid('getSetting', 'getRootNodes').apply(this, [$(this).treegrid('getTreeContainer')]);
            },
            /**
             * Method return all nodes of tree.
             *
             * @returns {Array}
             */
            getAllNodes: function() {
                return $(this).treegrid('getSetting', 'getAllNodes').apply(this, [$(this).treegrid('getTreeContainer')]);
            },
            /**
             * Mthod return true if element is Node
             *
             * @returns {String}
             */
            isNode: function() {
                return $(this).treegrid('getNodeId') !== null;
            },
            /**
             * Mthod return id of node
             *
             * @returns {String}
             */
            getNodeId: function() {
                if ($(this).treegrid('getSetting', 'getNodeId') === null) {
                    return null;
                } else {
                    return $(this).treegrid('getSetting', 'getNodeId').apply(this);
                }
            },
            /**
             * Method return parent id of node or null if root node
             *
             * @returns {String}
             */
            getParentNodeId: function() {
                return $(this).treegrid('getSetting', 'getParentNodeId').apply(this);
            },
            /**
             * Method return parent node or null if root node
             *
             * @returns {Object[]}
             */
            getParentNode: function() {
                if ($(this).treegrid('getParentNodeId') === null) {
                    return null;
                } else {
                    return $(this).treegrid('getSetting', 'getNodeById').apply(this, [$(this).treegrid('getParentNodeId'), $(this).treegrid('getTreeContainer')]);
                }
            },
            /**
             * Method return array of child nodes or null if node is leaf
             *
             * @returns {Object[]}
             */
            getChildNodes: function() {
                return $(this).treegrid('getSetting', 'getChildNodes').apply(this, [$(this).treegrid('getNodeId'), $(this).treegrid('getTreeContainer')]);
            },
            /**
             * Method return depth of tree.
             *
             * This method is needs for calculate indent
             *
             * @returns {Number}
             */
            getDepth: function() {
                if ($(this).treegrid('getParentNode') === null) {
                    return 0;
                }
                return $(this).treegrid('getParentNode').treegrid('getDepth') + 1;
            },
            /**
             * Method return true if node is root
             *
             * @returns {Boolean}
             */
            isRoot: function() {
                return $(this).treegrid('getDepth') === 0;
            },
            /**
             * Method return true if node has no child nodes
             *
             * @returns {Boolean}
             */
            isLeaf: function() {
                return $(this).treegrid('getChildNodes').length === 0;
            },
            /**
             * Method return true if node last in branch
             *
             * @returns {Boolean}
             */
            isLast: function() {
                if ($(this).treegrid('isNode')) {
                    var parentNode = $(this).treegrid('getParentNode');
                    if (parentNode === null) {
                        if ($(this).treegrid('getNodeId') === $(this).treegrid('getRootNodes').last().treegrid('getNodeId')) {
                            return true;
                        }
                    } else {
                        if ($(this).treegrid('getNodeId') === parentNode.treegrid('getChildNodes').last().treegrid('getNodeId')) {
                            return true;
                        }
                    }
                }
                return false;
            },
            /**
             * Method return true if node first in branch
             *
             * @returns {Boolean}
             */
            isFirst: function() {
                if ($(this).treegrid('isNode')) {
                    var parentNode = $(this).treegrid('getParentNode');
                    if (parentNode === null) {
                        if ($(this).treegrid('getNodeId') === $(this).treegrid('getRootNodes').first().treegrid('getNodeId')) {
                            return true;
                        }
                    } else {
                        if ($(this).treegrid('getNodeId') === parentNode.treegrid('getChildNodes').first().treegrid('getNodeId')) {
                            return true;
                        }
                    }
                }
                return false;
            },
            /**
             * Return true if node expanded
             *
             * @returns {Boolean}
             */
            isExpanded: function() {
                return $(this).hasClass('treegrid-expanded');
            },
            /**
             * Return true if node collapsed
             *
             * @returns {Boolean}
             */
            isCollapsed: function() {
                return $(this).hasClass('treegrid-collapsed');
            },
            /**
             * Return true if at least one of parent node is collapsed
             *
             * @returns {Boolean}
             */
            isOneOfParentsCollapsed: function() {
                var $this = $(this);
                if ($this.treegrid('isRoot')) {
                    return false;
                } else {
                    if ($this.treegrid('getParentNode').treegrid('isCollapsed')) {
                        return true;
                    } else {
                        return $this.treegrid('getParentNode').treegrid('isOneOfParentsCollapsed');
                    }
                }
            },
            /**
             * Expand node
             *
             * @returns {Node}
             */
            expand: function() {
                var trItem = $(this).data('obj');
                var isParent = trItem["isParent"],sync = trItem["sync"];
                if ( (!this.treegrid('isLeaf') && !this.treegrid("isExpanded") ) ) {
                    this.trigger("expand");
                    this.trigger("change");
                    return this;
                }
                if(( (isParent == 'true' || isParent == true)&&(!sync) )){
                    //判断第一次
                    var  isFirst = trItem['isFirst'];
                    if(isFirst){
                        $(this).treegrid('loadChildNodes');
                    }else{
                        trItem['isFirst'] = true;
                        $(this).data('obj',trItem);
                    }
                }
                return this;
            },
            /**
             * Expand all nodes
             *
             * @returns {Node}
             */
            expandAll: function() {
                var $this = $(this);
                $this.treegrid('getRootNodes').treegrid('expandRecursive');
                return $this;
            },
            /**
             * Expand current node and all child nodes begin from current
             *
             * @returns {Node}
             */
            expandRecursive: function() {
                return $(this).each(function() {
                    var $this = $(this);
                    $this.treegrid('expand');
                    if (!$this.treegrid('isLeaf')) {
                        $this.treegrid('getChildNodes').treegrid('expandRecursive');
                    }
                });
            },
            /**
             * Collapse node
             *
             * @returns {Node}
             */
            collapse: function() {
                return $(this).each(function() {
                    var $this = $(this);
                    if (!$this.treegrid('isLeaf') && !$this.treegrid("isCollapsed")) {
                        $this.trigger("collapse");
                        $this.trigger("change");
                    }
                });
            },
            /**
             * Collapse all nodes
             *
             * @returns {Node}
             */
            collapseAll: function() {
                var $this = $(this);
                $this.treegrid('getRootNodes').treegrid('collapseRecursive');
                return $this;
            },
            /**
             * Collapse current node and all child nodes begin from current
             *
             * @returns {Node}
             */
            collapseRecursive: function() {
                return $(this).each(function() {
                    var $this = $(this);
                    $this.treegrid('collapse');
                    if (!$this.treegrid('isLeaf')) {
                        $this.treegrid('getChildNodes').treegrid('collapseRecursive');
                    }
                });
            },
            /**
             * Expand if collapsed, Collapse if expanded
             *
             * @returns {Node}
             */
            toggle: function() {
                var $this = $(this);
                if ($this.treegrid('isExpanded')) {
                    $this.treegrid('collapse');
                } else {
                    $this.treegrid('expand');
                }
                return $this;
            },
            /**
             * Rendering node
             *
             * @returns {Node}
             */
            render: function() {
                return $(this).each(function() {
                    var $this = $(this);
                    var trItem = $this.data('obj'),
                        isParent = trItem['isParent'];
                    //if parent colapsed we hidden
                    if ($this.treegrid('isOneOfParentsCollapsed')) {
                        $this.hide();
                    } else {
                        $this.show();
                    }
                    if (!$this.treegrid('isLeaf') || (isParent == true || isParent == 'true') ) {
                        $this.treegrid('renderExpander');
                        $this.treegrid('getChildNodes').treegrid('render');
                    }
                });
            },
            /**
             * Rendering expander depends on node state
             *
             * @returns {Node}
             */
            renderExpander: function() {
                return $(this).each(function() {
                    var $this = $(this);
                    var expander = $this.treegrid('getSetting', 'getExpander').apply(this);
                    var trItem = $this.data('obj');
                    if (expander) {
                        
                        if (!$this.treegrid('isCollapsed')) {
                            expander.removeClass($this.treegrid('getSetting', 'expanderCollapsedClass'));
                            expander.addClass($this.treegrid('getSetting', 'expanderExpandedClass'));
                        } else {
                            expander.removeClass($this.treegrid('getSetting', 'expanderExpandedClass'));
                            expander.addClass($this.treegrid('getSetting', 'expanderCollapsedClass'));
                        }
                        //如果是父节点,且没有加载过数据,则关闭
                        if( (trItem["isParent"] == true ||trItem["isParent"] == 'true') && !trItem["async"]){
                            expander.removeClass($this.treegrid('getSetting', 'expanderExpandedClass'));
                            expander.addClass($this.treegrid('getSetting', 'expanderCollapsedClass'));
                        }else{
                            expander.removeClass($this.treegrid('getSetting', 'expanderCollapsedClass'));
                            expander.addClass($this.treegrid('getSetting', 'expanderExpandedClass'));
                        }
                    } else {
                        $this.treegrid('initExpander');
                        $this.treegrid('renderExpander');
                    }
                });
            }
        };
        $.fn.treegrid = function(method) {
            if (methods[method]) {
                return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
            } else if (typeof method === 'object' || !method) {
                return methods.initTree.apply(this, arguments);
            } else {
                $.error('Method with name ' + method + ' does not exists for jQuery.treegrid');
            }
        };
        /**
         *  Plugin's default options
         */
        $.fn.treegrid.defaults = {
            initialState: 'expanded',
            saveState: false,
            saveStateMethod: 'cookie',
            saveStateName: 'tree-grid-state',
            expanderTemplate: '<span class="treegrid-expander byyicon"></span>',
            indentTemplate: '<span class="treegrid-indent"></span>',
            expanderExpandedClass: 'icon-folder-open',
            expanderCollapsedClass: 'icon-folder-close',
            treeColumn: 0,
            //added
            idColumn : 'id',
            rootValue : "",                                                 //rootId value
            treedData: false,                                               //是否树化的数据
            parentColumn : 'parentId',                                      //父级ID
            sortColumn : null,
            ajaxParams : {},
            url : null,
            type : 'POST',
            striped : true,
            border:0,
            expandAll : true,
            single : false,//是单选还是多选,默认多选
            columns : [],
            checkOrRadio : 'check',//单选还是复选

            getExpander: function() {
                return $(this).find('.treegrid-expander');
            },
            getNodeId: function() {
                var template = /treegrid-([A-Za-z0-9_-]+)/;
                if (template.test($(this).attr('class'))) {
                    return template.exec($(this).attr('class'))[1];
                }
                return null;
            },
            getParentNodeId: function() {
                var template = /treegrid-parent-([A-Za-z0-9_-]+)/;
                if (template.test($(this).attr('class'))) {
                    return template.exec($(this).attr('class'))[1];
                }
                return null;
            },
            getNodeById: function(id, treegridContainer) {
                var templateClass = "treegrid-" + id;
                return treegridContainer.find('tr.' + templateClass);
            },
            getChildNodes: function(id, treegridContainer) {
                var templateClass = "treegrid-parent-" + id;
                return treegridContainer.find('tr.' + templateClass);
            },
            getTreeGridContainer: function() {
                return $(this).closest('table');
            },
            getRootNodes: function(treegridContainer) {
                var result = $.grep(treegridContainer.find('tr'), function(element) {
                    var classNames = $(element).attr('class');
                    var templateClass = /treegrid-([A-Za-z0-9_-]+)/;
                    var templateParentClass = /treegrid-parent-([A-Za-z0-9_-]+)/;
                    return templateClass.test(classNames) && !templateParentClass.test(classNames);
                });
                return $(result);
            },
            getAllNodes: function(treegridContainer) {
                var result = $.grep(treegridContainer.find('tr'), function(element) {
                    var classNames = $(element).attr('class');
                    var templateClass = /treegrid-([A-Za-z0-9_-]+)/;
                    return templateClass.test(classNames);
                });
                return $(result);
            },
            //Events
            onCollapse: null,
            onExpand: null,
            onChange: null,
            onSuccess : null,//数据加载成功
            onBefore : null,//加载数据前调用
            onError : null,//加载失败调用
            onClick : null//选中行调用

        };
    })(window.jQuery || byy.jquery);

    exports('treegrid',{
        version :'1.0.0',
        msg : '暂无扩展函数'
    });
});

附上BYYUI的链接: http://www.byyui.com

转载请注明出处: https://chrunlee.cn/article/jquery-treegrid-component.html


感谢支持!

赞赏支持
提交评论
评论信息 (请文明评论)
暂无评论,快来快来写想法...
推荐
在项目开发过程中,分页是少不了的,之前封装了一个分页组件,样式是基于bootstrap的样式,当然也可以自己来修改
关于jquery,他的核心特点就是无new构造和链式调用,这里根据网上的资料,自己简单理解下,有助于消化核心代码。
先记录下,不定哪天就查了..防止找不到或不全
最大公因数,也称最大公约数、最大公因子,指两个或多个整数共有约数中最大的一个。a,b的最大公约数记为(a,b),同样的,a,b,c的最大公约数记为(a,b,c),多个整数的最大公约数也有同样的记号。求最大公约数有多种方法,常见的有质因数分解法、短除法、辗转相除法、更相减损法。与最大公约数相对应的概念是最小公倍数,a,b的最小公倍数记为[a,b]。
错误:The operation is insecure . 在使用canvas的 toDataUrl的时候报错,看了很多资料,基本上都说是设置跨域,但是我一直都有的啊。其实,只是顺序错了,setAttribute('crossOrigin','Anonymous') 要在设置 src之前设置。
在页面中不同的frame之间进行相互调用的话,我们可以通过frame获取对应的window然后进行调用,但是如果是浏览器不同的tab之间呢?
web开发中,前台有时候会需要一个随机数或序列,通常来说,这个随机数可能只在当前页面中使用,并不需要太过严格,大体上重复率低即可。
在通过chrome浏览器来调用摄像头的时候发现getUserMedia报错,但是本地开发却没有问题,主要原因是https环境的问题。chrome 不允许在非https和非localhost下的非安全环境进行调用。