grid里面的一个列的格式渲染,用到了一个自定义的函数:
{
header : "Spending",
dataIndex : 'spending',
align : 'right',
renderer : CurrencyFormat()
函数的定义如下
var NumberReg = /(\d+)(\d{3})/;
var DEFAULT_CURRENCY = '$';
NumberFormat = function(v) { //这个函数是渲染一般的数值数据,如12345,显示为12,345
var whole = String(v);
while (NumberReg.test(whole)) {
whole = whole.replace(NumberReg, '$1' + ',' + '$2');
}
return whole;
}
CurrencyFormat = function(currency) { //这个函数是渲染金额数据,如12345,显示为$12,345
return function(v) { //[color=#FF0000]开始看不懂了,这个用法...currency、v如是参数到底是怎么传递的?(问题一)[/color]
var txt = NumberFormat(v);
if (!currency) {
currency = DEFAULT_CURRENCY;
}
if (v < 0) {
return "-" + currency + txt.substring(1);
} else {
return currency + txt;
}
}
}
第二个问题是:Extjs有没有自己定义好的渲染各种数据显示的方法,最常用的方法是怎么用的?
1.首先看renderer : CurrencyFormat()
根据column的api, renderer的期望值是一个
function(value, metaData, record, rowIndex, colIndex, store).
在渲染的时候,会调用每个cell的renderer (这里你可以看GridView的onRender源码)
2.再来看你的
[code="javascript"]
CurrencyFormat = function(currency) {
return
function(v) {
var txt = NumberFormat(v);
if (!currency) {
currency = DEFAULT_CURRENCY;
}
if (v < 0) {
return "-" + currency + txt.substring(1);
} else {
return currency + txt;
}
}
} [/code]
基于第一点,所以这里的CurrencyFormat() 必须返回一个function.
v就是这个function的第一个参数,形参.
而currency呢是用来构造这个function闭包的一个变量.
从你这段代码来看,是不必要的,
只需要直接:
[code="javascript"]
{
header : "Spending",
dataIndex : 'spending',
align : 'right',
renderer : function(value, metaData, record, rowIndex, colIndex, store) {
//这里很多写法也是不必要的,自己根据需求优化就ok了.
//这里还需要注意的是作用域问题
var txt = NumberFormat(value);
if (!value) {
currency = DEFAULT_CURRENCY;
}
if (value < 0) {
return "-" + currency + txt.substring(1);
} else {
return currency + txt;
}
}
}
[/code]
3.至于
[quote]第二个问题是:Extjs有没有自己定义好的渲染各种数据显示的方法,最常用的方法是怎么用的? [/quote]
在3.0里面有BooleanColumn, DateColumn, NumberColumn, TemplateColumn等.
在2.2你也可以类似的定义一些就ok了.
我来回答你的第二个问题:)
定义好的方法有很多
请参考api中 Ext.util.Format静态类
Ext.util.Format.usMoney(v);//把数字格式化成美元
还有好多,我就不一一列出来了