Extjs4--Ext.data.Store的多列排序和过滤器
Extjs经常使用Ext.data.Store对象。下面说明一下它的排序方式和过滤器的使用。
1.初始化时指定排序方式
可以指定多个列进行排序,可以指定排序方式。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="../ext-all.js"></script> <link rel="stylesheet" type="text/css" href="../resources/css/ext-all-debug.css" /> <title>Insert title here</title> <script type="text/javascript"> Ext.onReady(function(){ //Set up a model to use in our Store Ext.define('User', { extend: 'Ext.data.Model', fields: [ {name: 'firstName', type: 'string'}, {name: 'lastName', type: 'string'}, {name: 'age', type: 'int'}, {name: 'eyeColor', type: 'string'} ] }); //创建Store var store = Ext.create('Ext.data.Store', { model: 'User', autoLoad: true, //排序方式,可以多个字段排序 sorters: [{ //先按年龄降序 property: 'age', direction: 'DESC' }, { //后按名称升序 property: 'firstName', direction: 'ASC' }], data : [ {firstName: 'Ed', lastName: 'Spencer', age:31,'eyeColor':'blue'}, {firstName: 'Edddd', lastName: 'Spencer', age:31,'eyeColor':'Brown'}, {firstName: 'Ea', lastName: 'Spencer', age:31,'eyeColor':'blue'}, {firstName: 'Tommy', lastName: 'Maintz', age:41,'eyeColor':'Brown'}, {firstName: 'Aaron', lastName: 'Conran', age:32,'eyeColor':'blue'}, {firstName: 'Lucy', lastName: 'Conran', age:35,'eyeColor':'white'}, {firstName: 'Jamie', lastName: 'Avins', age:36,'eyeColor':'Brown'} ] }); //创建Grid var grid = Ext.create('Ext.grid.Panel', { width: 700, height: 200, title: 'ExtJS.com - Browse Forums', store: store, disableSelection: true, loadMask: true, // grid columns columns:[{ text: "firstName", dataIndex: 'firstName', flex: 1, sortable: false },{ text: "lastName", dataIndex: 'lastName', width: 100, hidden: false, sortable: true },{ text: "age", dataIndex: 'age', width: 70, align: 'right', sortable: true },{ text: "eyeColor", dataIndex: 'eyeColor', width: 150, sortable: true }], renderTo: Ext.getBody() }); }); </script> </head> <body> </body> </html>
运行结果:
2.通过Store对象进行设定
(1)简单过滤
//简单过滤:返回眼睛颜色为棕色的记录 store.filter('eyeColor', 'Brown');
结果:
(2)复杂过滤:
//复杂过滤,使用函数过滤 store.filter( function(item) { var brown = item.data.eyeColor.indexOf("Brown"); var blue = item.data.eyeColor.indexOf("blue"); if(brown>-1 || blue>-1 ){ return true; } return false; } );
结果:
(3)当我们想改变排序方式时,可以指定字段进行排序
//单一字段排序 store.sort('eyeColor', 'ASC');
(4)添加一种新的排序方式:
store.sorters.add(new Ext.util.Sorter({ property : 'shoeSize', direction: 'ASC' })); store.sort();