Javascript SlickGrid:使用DataView而不是原始数据的简单示例?
我正在使用SlickGrid,通过Ajax调用将数据直接绑定到网格。目前运行良好,网格动态更新且可排序,我正在为一列使用自定义格式化程序:Javascript SlickGrid:使用DataView而不是原始数据的简单示例?,javascript,jquery,datagrid,slickgrid,Javascript,Jquery,Datagrid,Slickgrid,我正在使用SlickGrid,通过Ajax调用将数据直接绑定到网格。目前运行良好,网格动态更新且可排序,我正在为一列使用自定义格式化程序: var grid; var columns = [{ id: "time", name: "Date", field: "time" }, { id: "rating", name: "Rating", formatter: starFormatter // custom formatter } ]; var options = {
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);
});
});
但是,我想根据数据的值将一个类应用于网格中的行,因此看起来我是这样做的。这种方法相当复杂,而且有各种额外的方法
请有人解释一下我是如何将数据
转换为数据视图
——无论是最初还是在Ajax重新加载时——同时保持网格可排序,并继续使用我的自定义格式化程序的?(我不需要知道如何应用该类,只需要知道如何使用DataView。)
我希望在
.getJSON
调用中增加一两行,但我担心它可能比这更复杂 关键是使用dataview作为数据源初始化网格,连接事件,以便网格响应dataview中的更改,并最终将数据提供给dataview。它应该是这样的:
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();
});
});
注意,您不需要每次都创建一个新的网格,只需将数据绑定到dataview即可
如果要实现排序,还需要在网格接收到排序事件时通知dataview进行排序:
grid.onSort.subscribe(function (e, args) {
sortcol = args.sortCol.field; // Maybe 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示例,但您可能希望实现一些自主开发的功能;例如,不使用全局变量)以下内容很好地解释了dataView:multiColumnSort:true==>sortCol类型:数组。
multiColumnSort:false==>sortCol类型:对象。谢谢!这实际上很有效,但有一个例外:在对网格进行排序时,我遇到了一个javascript错误:
uncaughttypeerror:cannotreadproperty'field'of undefined
。知道应该在哪里定义args.sortCol.field
吗?注意:我希望所有列都可以排序。听起来像是args.sortCol.field
属性引用中的输入错误。args参数被传递到onSort
回调。只需放置一个console.log(args)代码>并检查sortfield的正确属性名称(请参阅最新编辑)。确保仔细检查资本化。这些参数在最近的SlickGrid版本中已经更改,因此可能不完全正确。但基本上是正确的,这确实会对任何一列进行排序。你是对的,这是一个打字错误。这个答案再好不过了——谢谢你。