easyui treegrid 封装(不用分页,用加载更多按钮)延迟加载加加载更多

/**

 * @author wsf数据加载

 */

;

var intervalId = null;

(function (win,$){

    $.myCache = {

            dataCache : {},//数据缓存

            domOperCache:{}//dom操作缓存

    }

    /**

     * js执行时间测试

     */

    function test(fn,param){

        var s,d;

        s = new Date().getTime();

        fn(param);

        d = new Date().getTime();

        console.log('程序耗时:' + (d-s)/1000 + '秒');

    }

    /**

     * 检测屏幕分辨率

     */

    function screenWH() {  

          var w=screen.width;

          var h=screen.height;

          return {sw:w,sh:h};

    }  

    /**

     * 自定义加载方法

     */

    $.myLoader = function (){

        var swh = screenWH();//计算屏幕分辩率

        var is1024 = swh.sw == 1024;//是否是1024*768

        var w = ((swh.sw - 280)/6)-10;//计算过后的宽度

        this.page = "1";//初始分页参数

        this.rows = "50";//初始分页参数

        this.paramSearchPage = "1";//带参数查询分页

        this.paramSearchRows = "5";//带参数查询分页

        this.prevLoadPage = "1";//预先加载分页

        this.prevLoadRows = "5";//预先加载分页

        this.defaultLoadUrl = "/queryListLazy.do?";//初始化加载url

        this.paramLoadUrl = "/queryList.do?";//参数加载url

        this.searchType = "default";//默认为无参数搜索

        this.columns = [

                            {field:'FULLNAME',title:"客户全称",width:280,sortable:true},

                            {field:'SHORTNAME',title:'客户简称',width:w,sortable:true},

                            {field:'ECNNAME',title:'经济类型',width:w},

                            {field:'IDYNAME',title:'行业分类',width:w},

                            {field:'ZONNZME',title:'国家',width:w},

                            {field:'PROVNAME',title:'地区',width:w},

                            {field:'FN_DT',title:'成立日期',width:w},

                            {field:'HIGHTLIGHT',title:'是否高亮',hidden:true},

                            {field:'INST_ICN_NM',title:'logo名',hidden:true},

                            {field:'MAIN_BSN_MKT_LOT',title:'行业排名',hidden:true},

                            {field:'LGL_RPRT_NM',title:'董事长',hidden:true},

                            {field:'SNR_MGR_NM',title:'总经理',hidden:true}

                    ]

    }

    /**

     * 原型对象

     */

    $.myLoader.prototype = {

            constructor:$.myLoader,//构造函数

            /**

             * 公共渲染方法

             */

            commonRender:function (data,flag){

                var that = this;//防止this转变

                $("#content").treegrid({

                    //pagination:true,

                    animate:true,

                    collapsible:true,

                    fitColumns:true,

                    idField:'id',

                    treeField:'FULLNAME',

                    columns:[that.columns],

                    //展开前

                    onBeforeExpand:function (row){

                        that.gridBeforeExpand.apply(that,arguments);

                    },

                    //展开后

                    onExpand:function (row){

                        that.gridExpanded.apply(that,arguments);

                    },

                    //加载成功后

                    onLoadSuccess:function (row,data){

                        that.gridLoadSuccess.apply(that,arguments);

                    },

                    //双击行

                    onDblClickRow:function (){

                        that.dbClickRow.apply(that,arguments);

                    }

                });

                

                $('#content').treegrid('loadData',data);//渲染数据

                if(typeof flag == 'boolean'){

                }

            },

            /**

             * 初始进来加载

             */

            defaultLoad:function (data){

                this.commonRender(data,true);

                this.gridPagination();//设置分页bar

                this.changeGridStyle();//自定义样式

            },

            /**

             *带参数加载 

             */

            paramLoad:function (data){

                $('#content').treegrid('loadData',data);//渲染数据

                this.gridPagination();//设置分页bar

                this.changeGridStyle();//自定义样式

            },

            /**

             * 动态添加行

             */

            addRow:function (){

                var s,e;

                s = new Date().getTime();

                var that = this;

                var flag = this.searchType == "default";

                var _rowd = null;

                if(!flag){

                    _rowd = that.getParamSearchPageData();//有参数搜索

                }else{

                    _rowd = that.getPreLoadPageData();//无参数搜索

                }

                var i = 0 ,len = _rowd.length;

                if(len>0){

                    showNoImgMyLoading();

                    that.timeid = setTimeout(function (){

                        do{

                            var row = _rowd[i++];

                            var parentid = row._parentId;//父节点

                            $('#content').treegrid('append',{

                                parent:parentid,

                                data:[row]

                            });//添加行

                            if(i==len-1){

                                e = new Date().getTime();

                                console.log('程序耗时:' + (e-s)/1000 + '秒');

                            }

                        }while(i<len);

                        that.afterAppendRow.apply(that,arguments);

                    },100);

                }

            },

            /**

             * 添加行

             */

            appendRow:function (){

                

            },

            /**

             * 改变默认图标(添加行后)

             */

            afterAppendRow:function (){

                clearTimeout(this.timeid);

                closeLoading();

                var flag = (this.searchType == "default") && (this.rows/this.prevLoadRows == this.prevLoadPage);

                if(flag)

                   this.prevLoad();//预先加载

            },

            /**

             * 获得预先加载分页数据

             */

            getPreLoadPageData:function (){

                var rowData = $.myCache.dataCache["preLoadData"].rows;

                var page  = this.prevLoadPage;

                var pageSize = this.prevLoadRows;

                var start = page*pageSize-pageSize;

                var end = start+pageSize*1;

                this.prevLoadPage++;

                return rowData.slice(start,end);

            },

            /**

             * 带参数分页(前台)

             */

            getParamSearchPageData:function (){

                var _d = $.myCache.dataCache["paramData"].rows;

                var page = this.paramSearchPage;//当前页

                var pageSize = this.paramSearchRows;

                var start = page*pageSize-pageSize;

                var end = start+pageSize*1;

                this.paramSearchPage++;

                return _d.slice(start,end);

            },

            /**

             * grid展开事件

             */

            gridBeforeExpand:function (){

                var row = arguments[0];

                var _event = event||widow.event;

                var _target = _event.target||_event.srcElement;

                var _tr = $(_target).parents("tr");

                var isOpended = this.getDomOperCache(row.id);

                if(typeof isOpended != 'undefined'){

                }else{

                    this.expandTar = _tr;//鼠标点击了哪一行

                    //动态设置展开查询的url

                    var url = "/citics.crm/customerwidget/queryListLazy.do?parentId="+row.id;

                    $("#content").treegrid("options").url = url;

                }

                return true;

            },

            /**

             * grid展开后事件

             */

            gridExpanded:function (){

                var row = arguments[0];

                var _tr = this.expandTar;

                var isOpended = this.getDomOperCache(row.id);

                if(typeof isOpended != 'undefined'){

                }else{

                    //this.changeTreeIcon(_tr.next());//修改icon小图标

                    this.setDomOperCache(row.id,"alreadyOpened");//已经点开过

                }

            },

            /**

             * 设置分页控件

             */

            gridPagination:function (){

                var that = this;

                //设置分页控件&nbsp; 

            &nbsp;&nbsp;&nbsp;&nbsp;var page = $('#content').treegrid('getPager');&nbsp; 

                var opts = $('#content').treegrid('options'); 

            &nbsp;&nbsp;&nbsp;&nbsp;$(page).pagination({&nbsp; 

            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pageSize: 10,//每页显示的记录条数,默认为10&nbsp; 

            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pageList: [5,10,15],//可以设置每页记录条数的列表&nbsp; 

            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;beforePageText: '第',//页数文本框前显示的汉字&nbsp; 

            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;afterPageText: '页&nbsp;&nbsp;&nbsp; 共 {pages} 页',&nbsp; 

            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;displayMsg: '当前显示 {from} - {to} 条记录&nbsp;&nbsp; 共 {total} 条记录',&nbsp; 

            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;onBeforeRefresh:function(){ 

            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},

                    onSelectPage: function (pageNumber, pageSize) { 

                        opts.pageNumber = pageNumber;  

                        opts.pageSize = pageSize;  

                        that.page = pageNumber;//更新当前页

                        that.loader({page:pageNumber+"",rows:that.rows+""},0,true);

                    }

            &nbsp;&nbsp;&nbsp;&nbsp;});&nbsp;

            },

            /**

             * 前台分页

             */

            pagerFilter:function (data){

                var data = arguments[0];

                var dg = $(this);  

                var state = dg.data('treegrid');

                var opts = dg.treegrid('options');  

                var pager = dg.treegrid('getPager');  

                pager.pagination({  

                    onSelectPage:function(pageNum, pageSize){  

                        opts.pageNumber = pageNum;  

                        opts.pageSize = pageSize;  

                        pager.pagination('refresh',{  

                            pageNumber:pageNum,  

                            pageSize:pageSize  

                        });  

                        dg.treegrid('loadData',data);  

                    }  

                });  

                if (!data.topRows){  

                    data.topRows = [];

                    data.childRows = [];

                    for(var i=0; i<data.rows.length; i++){

                        var row = data.rows[i];

                        row._parentId ? data.childRows.push(row) : data.topRows.push(row);

                    }

                    data.total = (data.topRows.length);

                }  

                var start = (opts.pageNumber-1)*parseInt(opts.pageSize);  

                var end = start + parseInt(opts.pageSize);  

                data.rows = $.extend(true,[],data.topRows.slice(start, end).concat(data.childRows));

                return data;

            },

            /**

             * grid加载完成后

             */

            gridLoadSuccess:function (){

            },

            /**

             * 添加dom操作缓存

             * @param dom

             * @param flag

             */

            setDomOperCache:function (dom,flag){

                var _cache = $.myCache.domOperCache;

                _cache[dom] = flag;

            },

            /**

             * 获取dom操作缓存

             * @param dom

             * @param flag

             */

            getDomOperCache:function (dom){

                var _cache = $.myCache.domOperCache;

                return _cache[dom];

            },

            /**

             * 自定义修改grid样式

             */

            changeGridStyle:function (){

                this.changeGridHead();//改变表头样式

                this.changeGridFooter();//表脚样式

                if(typeof G_LIST == "boolean"){

                    //搜索列表(固定表头)

                    this.fixTh();//锁定表头

                    this.fixTbody();//锁定表体

                }

                //hightSearchedTr();//高亮显示与搜索条件相关的tr

            },

            /**

             * 改变表头样式

             */

            changeGridHead:function (){

                var gridHead = $(".datagrid-header");

                var gridHeadInner = $(".datagrid-header-inner");

                //grid头

                gridHead.css({

                    'background-image' : 'none',

                    'background-color' : '#ccddff',

                    'font-weight' : '900',

                    "border-left":"1px solid lightblue",

                    "border-right":"1px solid lightblue",

                    "border-top":"1px solid lightblue"

                });

                gridHeadInner.css('background-color','#ccddff');

            },

            /**

             * 改变表脚样式

             */

            changeGridFooter:function (){

                var gridFooter = $(".pagination");

                //grid表脚

                gridFooter.css({

                    'background-image' : 'none',

                    'background-color' : '#ccddff',

                });

            },

            /**

             * 改变grid样式(表体)

             */

            changeGridBody:function () {

                $("td").css({

                    "border-right":"none",

                    "border-bottom":"1px dotted lightblue"

                });

                $(".datagrid-body,.datagrid-wrap").css({

                    "border-color":"lightblue",

                    "border-bottom":"none",

                    "border-top":"none",

                });

                $("#expandBtn").click();//默认收起tree

            },

            /**

             * 设置grid高度

             */

            resizeGrid:function (){

                var _h = $(".datagrid-body > table > tbody > tr").filter(".datagrid-row").length*25;//

                $(".datagrid-wrap,.datagrid-view").height(_h);

            },

            /**

             * 自定义tree图标

             */

            /*

            changeTreeIcon:function (tar){

                var folder,file;

                if(!tar){

                    //整个表格

                    folder = $(".tree-folder");

                    file = $(".tree-file");

                }else{

                    //指定行

                    folder = tar.find(".tree-folder");

                    file = tar.find(".tree-file");

                    

                }

                folder.css({

                    "background-image":"url(/citics.crm/modules/customerwidget/images/user_add.png)",

                    "background-position":"0"

                });

                file.css({

                    "background-image":"url(/citics.crm/modules/customerwidget/images/user.png)",

                    "background-position":"0"

                });

            },*/

            /**

             * 锁定表头

             */

            fixTh:function (){

                var th = $(".datagrid-header");//表头

                var _top = $("#headWraper").height();

                setTimeout(function (){

                    var innerTop = $("#headWraper").height();

                    if(_top == innerTop){

                        th.css({

                            "position":'fixed',

                            "top":_top+"px"

                        });

                    }

                },200);

            },

            /**

             * 定位grid位置

             */

            fixTbody:function (){

                $(".datagrid").css("margin-top",($("#headWraper").height()+18)+"px");

            },

            /**

             * 双击行

             */

            dbClickRow:function (){

                var row = arguments[0];

                if(row) {

                    //客户组件客户双击

                    var param = {};

                    param["bpno"] = null;

                    param["custid"] = row.id;//客户主键

                    param["fullName"] = row.FULLNAME;//客户名称

                    win.singleViewParam = param;//传入单一视图的参数

                    win.open("/citics.crm/modules/customerwidget/singleview/singleview.jsp","_blank");

                }else{

                    alert("请选择一行进行修改!");

                    return;

                }

            },

            /**

             * 高亮显示与搜索条件相关的tr

             */

            hightlightSearchedTr:function (){

                var allTr = $("tr").filter(function (){

                    var kids = $(this).children();//最后一列

                    var flag = $.trim(kids.filter(":eq(7)").find("div").text()) == "Y";

                    return flag;

                });

                allTr.css({

                    "font-weight":700,

                    "color":"grey"

                });

            },

            /**

             * 前台处理数据

             */

            processData:function (data){

                var len = data.total;

                if(len>this.rows){

                    data.rows.splice(this.rows);

                }

            },

            //公共调用方法

            loader:function (param,parentId,flag,callback){

                var that = this;//防止this转换

                showMyLoading();

                var _url = (flag?this.defaultLoadUrl:this.paramLoadUrl)+"parentId="+parentId;

                $.ajax({

                    url:_url,

                    dataType:'json',

                    type:"post",

                    data:{

                        searchParam:JSON.stringify(param)

                    },

                    success:function (data){

                        if(data.total>0){

                            if(flag){

                                //初始化加载

                                that.searchType = "default";//无参数搜索

                                $.myCache.dataCache["noParamData"] = data;//缓存数据

                                that.defaultLoad(data);

                                that.loadAllCustName();//加载所有名称

                                that.prevLoad();//预先加载

                            }else{

                                $.myCache.dataCache["preLoadData"] = undefined;//清空初始化

                                $.myCache.dataCache["paramData"] = $.extend(true,{},data);//带参数数据缓存(深度copy)

                                $.myCache.dataCache["paramData"].rows.splice(0,that.rows);//删除初始进来的部分

                                that.searchType = "param";//带参数搜索

                                that.processData(data);//前台处理数据(模拟分页)(只渲染分页指定的条数)

                                //条件搜索

                                that.paramLoad(data);

                            }

                            if(data.total>that.rows){

                                intervalId = setInterval(function (){

                                    if(typeof $.myCache.dataCache["preLoadData"] != 'undefined'){

                                        clearInterval(intervalId);

                                        $("#loadMoreDiv").show()

                                    }else{

                                        $("#loadMoreDiv").hide()

                                    }

                                },500);

                            }

                            

                        }else{

                            $('#content').treegrid('loadData',data);//渲染数据

                            $("#loadMoreDiv").hide()

                        }

                        closeLoading();

                        if(callback)

                            callback();

                    },

                    error:function (a,b,c){

                        alert("加载列表出错:"+b);

                        closeLoading();

                    }

                });

            },

            /**

             * 预先加载一页

             */

            prevLoad:function (){

                var searchParam = JSON.stringify({page:(++this.page)+"",rows:this.rows});

                var _url = "/citics.crm/customerwidget/queryListLazy.do?parentId=0&searchParam="+searchParam;

                var that = this;

                $.getJSON(_url,function (data){

                    $.myCache.dataCache["preLoadData"] = data;//预先加载缓存数据

                    that.prevLoadPage = 1;//预先加载分页(重置)

                })

            },

            /**

             * 加载所有客户名称(缓存)

             */

            loadAllCustName:function (){

                $.getJSON("/citics.crm/customerwidget/queryAllCustName.do",function (data){

                    $.myCache.dataCache["allName"] = data;//缓存名称数据

                })

            }

            

    }

    

})(window,jQuery);

 

你可能感兴趣的:(treegrid)