日期:2014-05-16  浏览次数:20344 次

ExtJS 中文排序

摘自深入浅出ExtJs

?

Ext默认使用ASCII进行排序,为了让表格实现中文排序功能,需要重写Ext.data.Store的applySort函数

代码如下:

?

Ext.data.Store.prototype.applySort = function(){
				if(this.sortInfo && !this.remoteSort){
						var s = this.sortInfo,
						f = s.field;
						var st = this.fields.get(f).sortType;
						var fn = function(r1,r2){
							var v1 = st(r1.data[f]),v2 = st(r2.data[f]);
							if(typeof(v1) == 'string'){
									return v1.localeCompare(v2);
								}
							return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
							};
						this.data.sort(s.direction,fn);
						if(this.snapshot && this.snapshot != this.data){
								this.snapshot.sort(s.direction,fn);
							}
					}
			};

?

?可以将这段代码加到ext-all.js文件的最后,或者放到HTML页面的最上面,总之是要在EXT初始化之后,实际代码调用之前执行.

一般实现结构

?

Ext.data.Store.prototype.applySort = function(){
                ........................
}

Ext.onReady(function(){
           ................
});

?

?

?

完整示例代码:

?

Ext.onReady(function(){
		//中文排序功能,重写Ext.data.Store的applySort函数
		
		Ext.data.Store.prototype.applySort = function(){
				if(this.sortInfo && !this.remoteSort){
						var s = this.sortInfo,
						f = s.field;
						var st = this.fields.get(f).sortType;
						var fn = function(r1,r2){
							var v1 = st(r1.data[f]),v2 = st(r2.data[f]);
							if(typeof(v1) == 'string'){
									return v1.localeCompare(v2);
								}
							return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
							};
						this.data.sort(s.direction,fn);
						if(this.snapshot && this.snapshot != this.data){
								this.snapshot.sort(s.direction,fn);
							}
					}
			};
			



		
		//列定义:
		var cm = new Ext.grid.ColumnModel([
		                                   {header:'编号',dataIndex:'id'},
		                                   {header:'名称',dataIndex:'name'},
		                                   {header:'描述',dataIndex:'descn'}
			                           		]);

		var data2= [['1','啊','descn1'],
   		         	['2','啵','descn2'],
   		         	['3','呲','descn3'],
   		      		['4','嘚','descn4'],
   		  			['5','咯','descn5'],
   		    		];

		
   		//数据存储
   		var store = new Ext.data.Store({
			proxy: new Ext.data.MemoryProxy(data2),
			reader: new Ext.data.ArrayReader({},[
					{name:'id'},
					{name:'name'},
					{name:'descn'}
					]),
			sortInfo:{field:'name',direction:'ASC'}
   	   		});
	   //初始化数据	
	   store.load();
		   
  		var grid = new Ext.grid.GridPanel({
  	  		//enableColumnMove:false,  
  	  		//enableColumnResize:false,
  	  		//斑马显示效果
  	  		stripeRows:true,
  	  		//显示loding.....
  	  		loadMask:true,
  			autoHeight:true,
			renderTo:'grid',
			store:store,
			cm:cm

  		});
 			
	});
?

?

?