SlickGrid:使用 DataView 而不是原始数据的简单示例?

问题描述 投票:0回答:3

我正在使用 SlickGrid,通过 Ajax 调用将数据直接绑定到网格。目前它运行良好,网格动态更新并且可排序,并且我正在为一列使用自定义格式化程序:

var grid;
var columns = [{
  id: "time",
  name: "Date",
  field: "time"
},
{
  id: "rating",
  name: "Rating",
  formatter: starFormatter // custom formatter 
}
];
var options = {
  enableColumnReorder: false,
  multiColumnSort: true
};
// When user clicks button, fetch data via Ajax, and bind it to the grid. 
$('#mybutton').click(function() {
  $.getJSON(my_url, function(data) {
    grid = new Slick.Grid("#myGrid", data, columns, options);
  });
});

但是,我想根据数据值将类应用于网格中的行,因此看来我需要使用 DataView 来代替。 SlickGrid wiki 上的 DataView 示例相当复杂,并且有各种额外的方法。

请有人解释一下我如何简单地将

data

 转换为 
DataView
 - 最初和 Ajax 重新加载时 - 同时保持网格可排序,并继续使用我的自定义格式化程序? (我不需要知道如何应用该类,只需知道如何使用 DataView。)

我希望在

.getJSON

 调用中多加一两行,但我担心它可能比这更复杂。 

javascript jquery datagrid slickgrid
3个回答
20
投票
关键部分是使用数据视图作为数据源初始化网格,连接事件以便网格响应数据视图中的更改,最后将数据提供给数据视图。它应该看起来像这样:

dataView = new Slick.Data.DataView(); grid = new Slick.Grid("#myGrid", dataView, columns, options); // wire up model events to drive the grid dataView.onRowCountChanged.subscribe(function (e, args) { grid.updateRowCount(); grid.render(); }); dataView.onRowsChanged.subscribe(function (e, args) { grid.invalidateRows(args.rows); grid.render(); }); // When user clicks button, fetch data via Ajax, and bind it to the dataview. $('#mybutton').click(function() { $.getJSON(my_url, function(data) { dataView.beginUpdate(); dataView.setItems(data); dataView.endUpdate(); }); });
注意,不需要每次都创建新的网格,只需将数据绑定到数据视图即可。

如果你想实现排序,你还需要告诉数据视图在网格收到排序事件时进行排序:

grid.onSort.subscribe(function (e, args) { sortcol = args.sortCol.field; dataView.sort(comparer, args.sortAsc); }); function comparer(a, b) { var x = a[sortcol], y = b[sortcol]; return (x == y ? 0 : (x > y ? 1 : -1)); }
(这个基本排序取自 SlickGrid 示例,但您可能想要实现一些自制的东西;例如不使用全局变量)


2
投票
以下内容很好地解释了 dataView:

https://github.com/mleibman/SlickGrid/wiki/DataView


0
投票
multiColumnSort: true ==> sortCol 类型:数组。

multiColumnSort: false ==> sortCol 类型:对象。

© www.soinside.com 2019 - 2024. All rights reserved.