×
文章路径: WEB前端 > JS

DhtmlXGrid适配器

发表于1年前(Dec 15, 2016 12:07:59 PM)  阅读 584  评论 0

分类: WEB前端 JS

标签: bootstrap-table DhtmlXGrid DHtmlXGridJsonAdapter 适配器

DHX是一个国外的javascript库,包括了很多javscript插件,数据方面有关的就包括Chart、Tree、DataView、TreeGrid、Grid、TreeView、List。其中Grid算是用得比较多的了。

DhtmlXGrid有几个缺点,一般来说,都是后台组装好需要的xml数据,返回给前台使用,后台代码跟前台绑定太紧密,前台需要哪些字段,显示顺序是什么,后台都得事先考虑好。如果前台展示的顺序变了,后台代码也得跟着修改。对于不用显示,但后续操作可能需要用到的字段,像数据的主键这种,后台需要返回,前台通过设置隐藏实现,如果需要增加显示的字段,后台就也得改代码,非常不方便。

现在主流用的表格插件bootstrap-table提供的API就很好使用,这里笔者习惯了使用bootstrap-table,碰到项目需要使用DhtmlXGrid各种不爽,于是写了一个适配器,可以使用类bootstrap-table API的调用方式来生成DhtmlXGrid代码。

 

(function(){
	function DHtmlXGridJsonAdapter(options) {
		this.container = options.container;
		this.imagePath = options.imagePath;
		this.enableAutoHeight = options.enableAutoHeight;
		this.skin = options.skin;
		this.columns = options.columns;
		if(options.onDblClickRow) {
			this.onDblClickRow = options.onDblClickRow;
		}
		if(options.onClickRow) {
			this.onClickRow = options.onClickRow;
		}
		if(options.onEditCell) {
			this.onEditCell = options.onEditCell;
		}
		this._init();
		this.url = options.url;
		this.callback = options.callback;
		if(this.url!=undefined) {
			this.loadJson(this.url,this.callback);
		}
	};
	
	DHtmlXGridJsonAdapter.prototype._init = function() {
		var $obj = this;
		this.$grid = new dhtmlXGridObject(this.container);
		this.$grid.setImagePath(this.imagePath);
		this.$grid.enableAutoHeight(this.enableAutoHeight);
		this.$grid.setSkin(this.skin);
		
		var headerArray = new Array();
		var colTypeArray = new Array();
		var widthArray = new Array();
		var alignArray = new Array();
		var hiddenArray = new Array();
		for(var j=0;j<$obj.columns.length;j++) {
			var column = $obj.columns[j];
			var field = column.field;
			var width = column.width;
			if(width==undefined) {
				width = "*";
			}
			var colType = column.colType;
			if(colType==undefined) {
				colType = "ro";
			}
			var title = column.title;
			var rownum = column.rownum;
			var align = column.align;
			if(align==undefined) {
				align = "center";
			}
			var hidden = column.hidden;
			if(hidden) {
				hiddenArray.push(j);
				width = "0";
			}
			
			headerArray.push(title);
			colTypeArray.push(colType);
			widthArray.push(width);
			alignArray.push(align);
		}
		$obj.$grid.setHeader(headerArray.join(","));
		$obj.$grid.setColTypes(colTypeArray.join(","));
		$obj.$grid.setInitWidths(widthArray.join(","));
		$obj.$grid.setColAlign(alignArray.join(","));
		$obj.$grid.setColumnHidden(hiddenArray.join(","), true);
		
		
		if($obj.onClickRow) {
			$obj.$grid.attachEvent("onRowSelect", function(id,cind){
				$obj.onClickRow("onClickRow", id, cind, $obj.getRow(id));
			});
		}
		if($obj.onDblClickRow) {
			$obj.$grid.attachEvent("onRowDblClicked", function(id,cind){
				$obj.onDblClickRow("onDblClickRow", id, cind, $obj.getRow(id));
			});
		}
		if($obj.onEditCell) {
			$obj.$grid.attachEvent("onEditCell", function(stage,rId,cInd,nValue,oValue){
				return $obj.onEditCell(stage,rId,cInd,nValue,oValue);
			});
		}
		$obj.$grid.init();
	};
	
	/**
	 * 从指定url加载json数据,加载数据前会清除之前的数据。
	 */
	DHtmlXGridJsonAdapter.prototype.loadJson = function(url, callback) {
		var $obj = this;
		$obj.$grid.clearAll();
		$.ajax({
            type:"post",
            dataType:"json",
            cache:false,
            url:url,
            error:function(){
                alert("系统错误!");
            },
            success:function(data){
                var jsonData = $obj._setJsonFormat(data);
                var o = new Object();
                o.rows = jsonData;
                $obj.$grid.parse(o, callback, "json");
            }
        });
	};
	
	DHtmlXGridJsonAdapter.prototype._setJsonFormat = function(json) {
		var $obj = this;
		$obj.sourceData = new Object();
		$obj.index = new Array();
		var jsonData = new Array();
		for(var i=0;i<json.length;i++) {
			var dataObject = new Object();
			var data = json[i];
			var o = new Array();
			for(var j=0;j<$obj.columns.length;j++) {
				var column = $obj.columns[j];
				var field = column.field;
				var rownum = column.rownum;
				var value = eval("data."+field);
				var align = column.align;
				if(align==undefined) {
					align = "center";
				}
				var formatter = column.formatter;
				if(formatter!=undefined) {
					value = formatter(value, data, i);
				}
				if(rownum) {
					o.push(i+1);
				} else {
					if(value==undefined) {
						o.push("");
					} else {
						o.push(value);
					}
				}
			}
			var id = ""+(new Date()).valueOf()+i+j;
			$obj.index.push(id);
			dataObject.id = id
			dataObject.data = o;
			eval("$obj.sourceData[\""+id+"\"] = data;");
			jsonData.push(dataObject);
		}
		
		return jsonData;
	};
	
	/**
	 * 根据rowId获取行
	 */
	DHtmlXGridJsonAdapter.prototype.getRow = function (rowId) {
		var $obj = this;
		return eval("$obj.sourceData[\""+rowId+"\"]");
	};
	
	/**
	 * 根据索引值获取行,索引值即序号,从0开始
	 */
	DHtmlXGridJsonAdapter.prototype.getRowByIndex = function (index) {
		var $obj = this;
		return this.getRow($obj.index[index]);
	};
	
	/**
	 * 返回所选的行,当没有选择任何行的时候返回一个空数组。
	 */
	DHtmlXGridJsonAdapter.prototype.getSelections = function () {
		var $obj = this;
		var selectedId=$obj.$grid.getSelectedRowId();
		if(selectedId==undefined||selectedId=="") {
			return new Array();
		}
		var array = new Array();
		var selectedIds = selectedId.split(",");
		for(var i=0;i<selectedIds.length;i++) {
			array.push(this.getRow(selectedIds[i]));
		}
		return array;
	};
	
	/**
	 * 返回所有checked的行,当没有选择任何行的时候返回一个空数组。
	 */
	DHtmlXGridJsonAdapter.prototype.getCheckedRows = function (col_ind) {
		var $obj = this;
		var selectedId=$obj.$grid.getCheckedRows(col_ind);
		if(selectedId==undefined||selectedId=="") {
			return new Array();
		}
		var array = new Array();
		var selectedIds = selectedId.split(",");
		for(var i=0;i<selectedIds.length;i++) {
			array.push(this.getRow(selectedIds[i]));
		}
		return array;
	};

	/**
	 * 获取数据的总行数
	 */
	DHtmlXGridJsonAdapter.prototype.getRowCount = function () {
		var $obj = this;
		return $obj.index.length;
	};
	window.DHtmlXGridJsonAdapter = DHtmlXGridJsonAdapter;
}());

这个适配器已经做了常用的属性、接口、事件的适配,用户可以根据自己的需要增加其他方法的适配。使用时,在引入原来的DhtmlXGrid插件后引入适配器。

 

例子:

 

jQuery(function($) {
	dataListJsonGridbox = new DHtmlXGridJsonAdapter({
		container: "dataListGridbox",
		imagePath: ctx+"/js/dhtmlx3/imgs/",
		enableAutoHeight: false,
		url:"/list",
		skin: "dhx_skyblue",
		columns:[{
					title: '序号',
			        width: 40,
			        rownum: true
			    },{
			        field: 'TITLE',
			        title: '标题'
			    },{
			        field: 'MENUNAME',
			        title: '目录',
			        width: 120
			    },{
			        field: 'SCREENNAME',
			        title: '创建人',
			        width: 120
			    },{
			        field: 'CREATE_DATE',
			        title: '创建时间',
			        width: 160
			    },{
			        field: 'STATUS',
			        title: '状态',
			        width: 60,
			        formatter: statusFormatter
			    },{
			        field: 'SORT',
			        title: '排序',
			        width: 60
			    },{
				        title: '操作',
				        width: 120,
				        formatter: actionFormatter
			    }]
	});
	
});

function statusFormatter(value, row, index) {
	if(value=="0") {
		return "草稿";
	} else if(value=="1") {
		return "发布";
	} else if(value=="2") {
		return "删除";
	}
	return "";
}

function actionFormatter(value, row, index) {
	var action = new Array();
	action.push('<a style="color:blue" onclick="editPost(\''+row.ID+'\')">编辑</a>');
	if(row.STATUS=="0") {
		action.push('<a style="color:blue" onclick="postPost(\''+row.ID+'\')">发布</a>');
		action.push('<a style="color:blue" onclick="deletePost(\''+row.ID+'\')">删除</a>');
	} else if(row.STATUS=="1") {
		action.push('<a style="color:blue" onclick="draftPost(\''+row.ID+'\')">草稿</a>');
		action.push('<a style="color:blue" onclick="deletePost(\''+row.ID+'\')">删除</a>');
	} else if(row.STATUS=="2") {
		action.push('<a style="color:blue" onclick="postPost(\''+row.ID+'\')">发布</a>');
		action.push('<a style="color:blue" onclick="editPost(\''+row.ID+'\')">草稿</a>');
	}
	return action.join(" ");
}

 

 

发表评论