是否可以不区分大小写进行排序?
例如,默认排序显示如下:
Awesomeman
adam
beyonce
但是,我想这样排序:
adam
Awesomeman
beyonce
是否可以轻松覆盖灵敏度?据我所知,网格继承自 OnDemandGrid
和 OnDemandList
,它们都继承自 Grid
和 List
。对于我的商店,我正在使用包裹在 Observable
中的 Memory
。
截至目前,我正在尝试覆盖 List.js
中的 _setSort
,但这不起作用。有人熟悉这些框架吗?
最佳答案
可能有两种方法可以解决这个问题:
- 在网格端,通过处理和取消
dgrid-sort
事件 - 在商店端,通过扩展
query
强制sort
执行您想要的操作(首选)
首先是dgrid-sort
版本:
grid.on('dgrid-sort', function (event) {
// Cancel the event to prevent dgrid's default behavior which simply
// passes the sort criterion through to the store and updates the UI
event.preventDefault();
// sort is an array as expected by the store API, but dgrid's UI only sorts one field at a time
var sort = event.sort[0];
grid.set('sort', function (a, b) {
var aValue = a[sort.attribute].toLowerCase();
var bValue = b[sort.attribute].toLowerCase();
if (aValue === bValue) {
return 0;
}
var result = aValue > bValue ? 1 : -1;
return result * (sort.descending ? -1 : 1);
});
// Since we're canceling the event, we need to update the UI ourselves;
// the `true` tells it to also update dgrid's internal representation
// of the sort setting, so that toggling between asc/desc will still work
grid.updateSortArrow(event.sort, true);
});
虽然这适用于用户点击标题单元格时的处理,但它不会对程序化的 set('sort')
调用或 sort
的初始设置生效> 在传递给 Grid 构造函数的对象中,这可能会出现问题。
由于排序最终是一个商店问题,因此在商店端解决它确实是更可取的解决方案。无可否认,dojo/store/Memory
即 dojo/store/util/SimpleQueryEngine
并不能使这...嗯...简单...但需要注意一件事关于 SimpleQueryEngine
的是,如果您通过 queryOptions.sort
而不是数组传递一个函数,它将被逐字应用为要使用的排序函数。
这意味着我们可以采用 dgrid 将设置的传入 sort
数组,编写我们自己版本的 SimpleQueryEngine
的默认排序功能,同时考虑不区分大小写,并将其存储在继承调用的 queryOptions.sort
中:
var CIMemory = declare(Memory, {
query: function (query, queryOptions) {
var sort = queryOptions && queryOptions.sort;
if (sort) {
// Replace sort array with a function equivalent that performs
// case-insensitive sorting
queryOptions.sort = function (a, b) {
for (var i = 0; i < sort.length; i++) {
var aValue = a[sort[i].attribute].toLowerCase();
var bValue = b[sort[i].attribute].toLowerCase();
if (aValue !== bValue) {
var result = aValue > bValue ? 1 : -1;
return result * (sort[i].descending ? -1 : 1);
}
}
return 0;
}
}
return this.inherited(arguments);
}
});
使用它代替 dojo/store/Memory
将导致所有排序不区分大小写。
请注意,我在 SimpleQueryEngine
的 sort
函数上使用了一些快捷方式(检查 null/undefined 并将值强制转换为原语)。如果您需要担心这两件事,请根据需要更改排序功能。
关于javascript - dojo dgrid 中的非区分大小写排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26783489/