首页 Javascript 正文
429

jsGrid实现带有复位功能的表格排序

首先说一下要达到的排序效果:第一次点击列头按升序排,第二次按降序排列,第三次回到原始状态。
这里用到的是功能很丰富的jsGrid插件,项目地址: https://github.com/tabalinas/jsgrid
jsGrid本身只提供升序/降序切换排序,所以需要进行Hack。
基本思路:给每一行数据加入一个Index列,其序号代表了数据的原始顺序,并且此列数据不呈现出来,只负责数据顺序复位。
Hack代码如下 :
var data = [
                {
                    "Name": "Cara Rios",
                    "Age": 58,
                    "Index": 0
                },
                {
                    "Name": "Austin Andrews",
                    "Age": 55,
                    "Index": 1
                },
                {
                    "Name": "Lillian Peterson",
                    "Age": 39,
                    "Index": 2
                },
                {
                    "Name": "Adria Beach",
                    "Age": 29,
                    "Index": 3
                },
                {
                    "Name": "Oleg Durham",
                    "Age": 80,
                    "Index": 4
                }];
            var oldsort = jsGrid.Grid.prototype._sortData;
            function onSorted(sortField){
                if (!sortField.hasOwnProperty('counter')) return this;
                sortField.counter++;
                if (sortField.counter % 3 == 0) {
                    sortField.counter = 0;
                    this.sort({field:'Index', order:'asc'});
                    this._resetSorting();
                }
            };
            jsGrid.Grid.prototype._sortData = function(){
                oldsort.apply(this, arguments);
                typeof this.onSorted === 'function' && this.onSorted(this._sortField);
            };
            jsGrid.sortStrategies.withReset = function (value1, value2){
                if (!this.hasOwnProperty('counter')) {
                    this.counter = 0;
                }
                if (this.counter % 3 == 2) {
                    return 0;
                } else {
                    return value1.localeCompare(value2);
                }
            };
            var grid = new jsGrid.Grid($('#jsGrid'), {
                width: "100%", 
                height: "50%", 
                sorting: true,
                data:data,
                onSorted: onSorted, 
                //controller: db, 
                fields:[
                    { name: "Index", type: "number", visible: false }, 
                    { name: "Name", type: "text", width: 150, sorter: 'withReset'},
                    { name: "Age", type: "number", width: 50 }
                ]
            });

正在加载评论...