结合dwr的yui-ext分页例子

   最近接触yui-ext,被它漂亮的界面征服,于是想把它运用到项目里面。
公司目前是用dwr来实现一些简单的ajax功能,想把yui-ext结合dwr,但目前网上还很少有这样的例子,参考了yui-ext论坛里面的文章,做了一个简单的分页例子(下载)
    dwrproxy.js,这里只需要修改很少的地方。   

Ext.data.DWRProxy  =  function(dwrCall, pagingAndSort) {
  Ext.data.DWRProxy.superclass.constructor.call(
this);
  
this.dwrCall = dwrCall;
  
//this.args = args;
    this.pagingAndSort = (pagingAndSort!=undefined ? pagingAndSort : true);
}
;

Ext.extend(Ext.data.DWRProxy, Ext.data.DataProxy, 
{
  load : function(params, reader, callback, scope, arg) 
{
    
if(this.fireEvent("beforeload"this, params) !== false{
      var sort;
      
if(params.sort && params.dir) sort = params.sort + ' ' + params.dir;
      
else sort = '';
      var delegate 
= this.loadResponse.createDelegate(this, [reader, callback, scope, arg], 1);
      var callParams 
= new Array();
    
        
            
//if(this.pagingAndSort) {
          
//callParams.push(params.start);
          
//callParams.push(params.limit);
          
//callParams.push(sort);
            
//}

      
//这里的arg.params包含了分页时用到的基础参数和用户查询时自定义的参数    
      callParams.push(arg.params);
      callParams.push(delegate);
      
     
//console.debug(callParams);         
     
      
this.dwrCall.apply(this, callParams);
    
    }
 else {
      callback.call(scope 
|| thisnull, arg, false);
    }

  }
,

  loadResponse : function(listRange, reader, callback, scope, arg) 
{
    var result;
    
//console.debug(listRange); 
    try {
      result 
= reader.read(listRange);
    }
 catch(e) {
      
this.fireEvent("loadexception"thisnull, response, e);
      callback.call(scope, 
null, arg, false);
      
return;
    }

    callback.call(scope, result, arg, 
true);
  }
,

  update : function(dataSet)
{},

  updateResponse : function(dataSet)
  
{}
}
);

Ext.data.ListRangeReader 
=  function(meta, recordType) {
    Ext.data.ListRangeReader.superclass.constructor.call(
this, meta, recordType);
    
this.recordType = recordType;
}
;
Ext.extend(Ext.data.ListRangeReader, Ext.data.DataReader, 
{
  getJsonAccessor: function()
{
      var re 
= /[/[/.]/;
      
return function(expr) {
          
try {
              
return(re.test(expr))
                  
? new Function("obj""return obj." + expr)
                  : function(obj)
{
                      
return obj[expr];
                  }
;
          }
 catch(e){}
          
return Ext.emptyFn;
      }
;
  }
(),
    
    read : function(o)
{
        var recordType 
= this.recordType, fields = recordType.prototype.fields;

        
//Generate extraction functions for the totalProperty, the root, the id, and for each field
        if (!this.ef) {
            
if(this.meta.totalProperty) {
                
this.getTotal = this.getJsonAccessor(this.meta.totalProperty);
            }

        
            
if(this.meta.successProperty) {
                
this.getSuccess = this.getJsonAccessor(this.meta.successProperty);
            }


            
if (this.meta.id) {
                var g 
= this.getJsonAccessor(this.meta.id);
                
this.getId = function(rec) {
                    var r 
= g(rec);
                    
return (r === undefined || r === ""? null : r;
                }
;
            }
 else {
                
this.getId = function(){return null;};
            }

            
this.ef = [];
            
for(var i = 0; i < fields.length; i++){
                f 
= fields.items[i];
                var map 
= (f.mapping !== undefined && f.mapping !== null? f.mapping : f.name;
                
this.ef[i] = this.getJsonAccessor(map);
            }

        }


       var records 
= [];
       var root 
= o.data, c = root.length, totalRecords = c, success = true;

       
if(this.meta.totalProperty){
        var v 
= parseInt(this.getTotal(o), 10);
            
if(!isNaN(v)){
                totalRecords 
= v;
            }

        }


        
if(this.meta.successProperty){
            var v 
= this.getSuccess(o);
            
if(v === false || v === 'false'){
                success 
= false;
            }

        }


        
for(var i = 0; i < c; i++){
        var n 
= root[i];
      var values 
= {};
      var id 
= this.getId(n);
      
for(var j = 0; j < fields.length; j++){
                f 
= fields.items[j];
        var v 
= this.ef[j](n);                        
        values[f.name] 
= f.convert((v !== undefined) ? v : f.defaultValue);
      }

      var record 
= new recordType(values, id);
      records[i] 
= record;
    }


    
return {
       success : success,
       records : records,
       totalRecords : totalRecords
    }
;
  }

}
);


     paging.js,分页时的调用的写法。
  

/*

 * Ext JS Library 1.0.1

 * Copyright(c) 2006-2007, Ext JS, LLC.

 * licensing@extjs.com

 * 

 * 
http://www.extjs.com/license

 
*/




Ext.onReady(function()
{


    var recordType 
= Ext.data.Record.create([

        
{name: "id", type: "int"},

        
{name: "department", type: "string"},

        
{name: "operator", mapping:"operator.pname", type: "string"},

        
{name: "content", mapping:"content", type: "string"}

      ]);

          
    
// create the Data Store
    var ds = new Ext.data.Store({
        
// load using DWRProxy
        proxy: new Ext.data.DWRProxy(MeetingService.findMeetingby, true),

        
// create reader that reads the Topic records
        reader: new Ext.data.ListRangeReader({
            totalProperty: 
'totalSize',
            id: 
'id'
        }
, recordType),

        
// turn on remote sorting
        remoteSort: true
    }
);
    
//ds.setDefaultSort('department', 'desc');

    
// pluggable renders
    function renderTopic(value, p, record){
        
return String.format('<b>{0}</b>{1}', value, record.data['operator']);
    }

    function renderTopicPlain(value)
{
        
return String.format('<b><i>{0}</i></b>', value);
    }

    function renderLast(value, p, r)
{

        
return String.format('{0}<br/>by {1}', value, r.data['department']);
    }

    function renderLastPlain(value)
{
        
return value;
    }


    
// the column model has information about grid columns
    
// dataIndex maps the column to the specific data field in
    
// the data store
    var cm = new Ext.grid.ColumnModel([{
           id: 
'department'// id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
           header: "部门",
           dataIndex: 
'department',
           width: 
150,
           renderer: renderTopic,

           sortable: 
true,
           css: 
'white-space:normal;'
        }
,{
           header: 
"操作人",
           dataIndex: 
'operator',
           width: 
150,

           sortable: 
true,
           hidden: 
false        //    隐藏列
        }
,{
           id: 
'content',
           header: 
"内容",
           dataIndex: 
'content',
           width: 
250,

           sortable: 
true,
           renderer: renderLast
        }
]);

    
// by default columns are sortable
    
//cm.defaultSortable = true;

    
// create the editor grid
    var grid = new Ext.grid.Grid('meeting-grid'{
        ds: ds,
        cm: cm,
        selModel: 
new Ext.grid.RowSelectionModel({singleSelect:true}),
        enableColLock:
false,
        loadMask: 
true    //是否显示正在加载
    }
);

    
// make the grid resizable, do before render for better performance
    var rz = new Ext.Resizable('meeting-grid'{
        wrap:
true,
        minHeight:
100,
        pinned:
true,
        handles: 
's'
    }
);
    rz.on(
'resize', grid.autoSize, grid);

    
// render it
    grid.render();

    var gridFoot 
= grid.getView().getFooterPanel(true);

    
// add a paging toolbar to the grid's footer
    var paging = new Ext.PagingToolbar(gridFoot, ds, {
        pageSize: 
5,
        displayInfo: 
true,
        displayMsg: 
'显示 {0} - {1} of {2}',
        emptyMsg: 
"没有记录"
    }
);
    
// add the detailed view button
    paging.add('-'{
        pressed: 
true,
        enableToggle:
true,
        text: 
'详细信息',
        cls: 
'x-btn-text-icon details',
        toggleHandler: toggleDetails
    }
);

    
// trigger the data store load
   
// ds.load({params:{start:0, limit:5}, extraParams:{dept:'test', viaParam:true}});        

    
//ds.load({params:{start:0, limit:5, department:'test', viaPara:true}});    

    
//ds.load({params:{start:0, limit:5}});    

    

    
//查询时需要用到的参数

    ds.on(
'beforeload', function() {

          ds.baseParams 
= {

            dept: 
'test111',

            viaParam: 
true

          }
;

        }
);    

    
//分页基本参数    

    ds.load(
{params:{start:0, limit:5}});    

        

    function toggleDetails(btn, pressed)
{
        cm.getColumnById(
'department').renderer = pressed ? renderTopic : renderTopicPlain;
        cm.getColumnById(
'content').renderer = pressed ? renderLast : renderLastPlain;
        grid.getView().refresh();
    }

}
);

 

  dwr调用后台的处理方式:

public  ListRange findMeetingby(Map condition)  {
        
// TODO Auto-generated method stub
        int totalRecords = getContentCount();
        HQuery hquery 
= new HQuery();
        hquery.setPageStartNo(Integer.parseInt(condition.get(
"start").toString()));
        hquery.setNumberPerPages(Integer.parseInt(condition.get(
"limit").toString()));
        hquery.setQueryString(
"from Meeting as a ");
        StringBuffer sb 
= new StringBuffer();
        sb.append(
"order by ");
        
if(condition.get("sort"!= null && condition.get("dir"!= null){
            sb.append(
"a.");
            sb.append(condition.get(
"sort"));
            sb.append(
" ");
            sb.append(condition.get(
"dir"));
        }
else
            sb.append(
"a.lastModifiedDate desc");
        
        hquery.setOrderby(sb.toString());
        List ls 
=  this.getBaseDao().executeQuery(hquery);
        
return new ListRange(ls.toArray(), totalRecords);
    }

   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值