最近接觸yui-ext,被它漂亮的界面征服,于是想把它運(yùn)用到項(xiàng)目里面。
公司目前是用dwr來(lái)實(shí)現(xiàn)一些簡(jiǎn)單的ajax功能,想把yui-ext結(jié)合dwr,但目前網(wǎng)上還很少有這樣的例子,參考了yui-ext論壇里面的文章,做了一個(gè)簡(jiǎn)單的分頁(yè)例子
(下載)。
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包含了分頁(yè)時(shí)用到的基礎(chǔ)參數(shù)和用戶(hù)查詢(xún)時(shí)自定義的參數(shù)
callParams.push(arg.params);
callParams.push(delegate);
//console.debug(callParams);
this.dwrCall.apply(this, callParams);

} else
{
callback.call(scope || this, null, arg, false);
}
},


loadResponse : function(listRange, reader, callback, scope, arg)
{
var result;
//console.debug(listRange);

try
{
result = reader.read(listRange);

} catch(e)
{
this.fireEvent("loadexception", this, null, 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,分頁(yè)時(shí)的調(diào)用的寫(xiě)法。

/**//*

* 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: "部門(mén)",
dataIndex: 'department',
width: 150,
renderer: renderTopic,

sortable: true,
css: 'white-space:normal;'

},
{
header: "操作人",
dataIndex: 'operator',
width: 150,

sortable: true,
hidden: false // 隱藏列

},
{
id: 'content',
header: "內(nèi)容",
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: "沒(méi)有記錄"
});
// add the detailed view button

paging.add('-',
{
pressed: true,
enableToggle:true,
text: '詳細(xì)信息',
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}});


//查詢(xún)時(shí)需要用到的參數(shù)


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


ds.baseParams =
{

dept: 'test111',

viaParam: true

};

});

//分頁(yè)基本參數(shù)


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調(diào)用后臺(tái)的處理方式:

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);
}
posted on 2007-06-05 09:30
凍僵的魚(yú) 閱讀(8524)
評(píng)論(33) 編輯 收藏