grid.js 6.92 KB
/*
*
*使用方法
*
*<div id="id"></div>
**/

/*var g=new grid({
    el:"#id",
    columns:[
        {display:"性别",name:"sex"},
        {display:"全名",name:"name",render:function(item){
            return item.xingshi+item.name;
        }}
    ]

});
g.init('url');*/


var $=require('jquery');
require('../util/jquery.simplePagination');

var grid=function(options){
    var defaults={
        size:10,
        innerHtml:"<div class='grid'><table class='table table-striped table-bordered responsive dataTable no-footer' role='grid' aria-describedby='basicTable_info'>"
                +"<thead></thead><tbody></tbody></table></div>"
                +"<nav><ul class='pagination'></ul></nav>",
        tabUrl: false
    }
    this.options=$.extend({}, defaults, options);
    this.grid=$(options.el);
}

grid.prototype={
    constructor:grid,
    
    init:function(url){
        var g = this, p = this.options;
        p.url=url;
        g.grid.html(p.innerHtml);
        g.table = $("table", g.grid);
        g.thead = $("thead", g.grid);
        g.tbody = $("tbody", g.grid);
        g.pagination=$(".pagination", g.grid);
        g.records = [];
        g.rows = [];
        g.selected = [];

        g.clear();
        g.renderHead();
        g.renderBody();
        // g.renderTab();
    },
    renderBody:function(){
        var g = this, p = this.options;
        g.__bodyload();
    },
    __bodyload:function(){
        var g = this, p = this.options;
        var _p = g.__getparams();
        if (_p == null) {
            var json = {page: 0,total:0};
            g.__pagination(json);
            return;
        } else {
            g.clear();
            g.ajax(_p);
        }
    },
    __getparams:function(){
        var g = this, p = this.options;
        
        var param = {},
            urlParam = {},
            urlArr = location.hash.substring(1).split('&&');

        if (p.parms) {
            if (typeof (p.parms) == "function") {
                param = p.parms();
            }
        }

        $.each(urlArr, function(i, value){
            var result = value.split('='),
                key = result[0],
                value = result[1];

            if (key) {
                urlParam[key] = value;
                
            }
        });

        if (!p.page && !urlParam.page) p.page = 1;

        if (param.page !== p.page) {
            param.page = p.page;
        } else {
            param.page = urlParam.page;
        }

        param.size = p.size;

        var urlHash = '';
        $.each(param, function(key, value) {
            if (value || value == '0') {
                urlHash += key + '=' + value + '&&';
            }
        });
        location.hash = urlHash;

        return param;
    },
    __pagination:function(pagination){
        var g = this, p = this.options;
        g.pagination.pagination({
            items: pagination.total,
            itemsOnPage: 5,
            pages: pagination.total,
            currentPage: pagination.page,
            edges: 1,
            hrefTextPrefix: '#page=',
            ellipsePageSet: false,
            onPageClick: function(pageNumber, event) {
                p.page = pageNumber;
                g.renderBody();
                return false;
            }
        });
    },
    renderHead:function(){
        var g = this, p = this.options;
        g.__headerClomun();
    },
    clear:function(){
        var g = this, p = this.options;
        g.tbody.html("");
        g.records = [];
        g.rows = [];
        g.selected = [];
    },
    __headerClomun:function(){
        var g = this, p = this.options;
        var tr = $("<tr></tr>");
        $(p.columns).each(function (i, column) {
            var td = g.__headerCell(column);
            tr.append(td);
        })
        g.thead.append(tr);
    },
    __headerCell:function(column){
        var g = this, p = this.options;
        var c = $("<th></th>");
        if (column.width) {
            c.attr("width", column.width);
        }
        if (column.name) c.attr({ columnname: column.name });
        var h_t = column.display || "";
        c.html(h_t);
        return column.hidden?"":c;
    },
    ajax:function(param){
        var g = this, p = this.options;
        var ajaxOptions = {
            type: 'POST',
            url: p.url,
            data: param,
            dataType: 'json',
            beforeSend: function () {
                //发送请求
            },
            success: function (res) {
                var data = res.data.data;

                g.__pagination({total:data.totalPage,page:data.page});
                g.__bodyClomun(data.list);
                // setpage(res);
            },
            complete: function () {
                console.log("complete~~");
            },
            error: function () {
                console.log("error~~");
                g.__pagination({total:0,page:0});
            }
        };
        $.ajax(ajaxOptions);
    },
    __bodyClomun:function(rows){
        var g = this, p = this.options;
        g.tbody.html("");
        if (!rows) { return ""; }                    ;
        var _r = [], _count = 0;
        
        function _r_num() {
            return (p.page - 1) * parseInt(p.rp);
        }
        if (rows.length > 0) {
            for (var row in rows) {
                var item = rows[row], _h = "";
                var num = _r_num() + _count;
                item._num = _count;
                item.rowid = "wqt_" + num + "_" + _count;
                if (!item) continue;
                _h += ('<tr >');
                g.records.push(_count);
                item.__index=_count;
                g.rows.push(item);
                $(p.columns).each(function (i, column) {
                    if(!column.hidden)
                    {
                        _h += ('<td >');
                        _h += (g.__bodyCell(item, column));
                        _h += ('</td>');
                    }
                })
                _h += ('</tr>');
                
                _r.push(_h);
                _count++;
                g.tbody.html(_r.join(''));
            }
        } else {
            var _h = "";
            _h += ('<tr >');
            _h += ('<td colspan=' + p.columns.length + '>');
            _h += ('<p class="nodata-tip">' + (p.msg?p.msg:"没有查询到数据") + '</p>');
            _h += ('</td>');
            _h += ('</tr>');
            _r.push(_h);
            g.tbody.html(_r.join(''));
        }
    },
    __bodyCell:function(row, col){
        var g = this, p = this.options;
        if (!row || !col) return "";
        var value = col.name ? row[col.name] : null;
        var content = "";
        if (col.render) {
            content = col.render.call(g, row, value, col);
        } else {
            content = value;
        }
        return content || "";
    },
    reload:function(param){
        var g = this, p = this.options;
        p.page=1;
        // g.renderTab();
        g.__bodyload();
    },

}

module.exports=grid;