본문 바로가기
Javascript

[JS] SlickGrid 단순 정렬하기

by Dokon Jang 2021. 3. 12.
반응형

SlickGrid의 타이틀을 클릭하며 정렬이 되는데 이것을 구현하는 방법입니다.

1. 컬럼 정의에 정렬 할 컬럼에 "sortable: true"를 지정합니다.

var columns = [
	{id: "no", name: "No", field: "no", sortable: true},
	{id: "title", name: "Title", field: "title", width:300, sortable: true},
	{id: "creator", name: "Creator", field: "creator", width:150, sortable: false}
];

 

2. SlickGrid의 onSort 이벤트를 아래와 같이 구현합니다.

grid.onSort.subscribe(function (e, args) {
	
	data.sort(function (dataRow1, dataRow2) {
		var field = args.sortCol.field;
		var sign = args.sortAsc ? 1 : -1;
		var value1 = dataRow1[field];
		var value2 = dataRow2[field];
		
		var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
		return result;
	});

	grid.invalidate();
	grid.render();
});

 

3. 아래의 이미지는 실행 결과입니다.

[정렬 전]

[정렬 후]

 

[전체 소스]

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Start Slick Grid</title>
	<link rel="stylesheet" href="js/slickgrid/slick.grid.css" type="text/css"/>
	<link rel="stylesheet" href="js/slickgrid/css/smoothness/jquery-ui.css" type="text/css"/>
	
	<script src="js/slickgrid/lib/jquery-1.12.4.min.js"></script>
	<script src="js/slickgrid/lib/jquery.event.drag-2.3.0.js"></script>
	
	<script src="js/slickgrid/slick.core.js"></script>
	<script src="js/slickgrid/slick.grid.js"></script>
	
	<script>
	$(document).ready(function () {
		// 컬럼
		var columns = [
		    {id: "no", name: "No", field: "no", sortable: true},
		    {id: "title", name: "Title", field: "title", width:300, sortable: true},
		    {id: "creator", name: "Creator", field: "creator", width:150, sortable: false}
		];
		
		// 옵션
		var options = {
			enableColumnReorder: false
		};
		
		// 데이터(json)
		var data = [
			{ no: 1, title: "Title 1", creator:"Creator 1"},
			{ no: 2, title: "Title 2", creator:"Creator 2"},
			{ no: 3, title: "Title 3", creator:"Creator 3"}
		];
		
		// SlickGrid 생성
		var grid = new Slick.Grid("#myGrid", data, columns, options);
		
		// 정렬
		grid.onSort.subscribe(function (e, args) {
			
			data.sort(function (dataRow1, dataRow2) {
				var field = args.sortCol.field;
				var sign = args.sortAsc ? 1 : -1;
				var value1 = dataRow1[field];
				var value2 = dataRow2[field];
				
				var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
				return result;
			});

			grid.invalidate();
			grid.render();
		});
	});
	</script>
</head>
<body>
	<div id="myGrid" style="width:600px;height:500px;"></div>
</body>
</html>
반응형

댓글