jqGrid自定义格式化程序

时间:2010-05-21 13:53:58

标签: jquery jqgrid

对于我的jqGrid中的一个列,我提供了一个自定义格式化程序函数。我提供了一些特殊情况,但是如果不满足这些条件,我想使用内置的日期格式化程序实用程序方法。我似乎没有得到$ .extend()的正确组合来创建方法所期望的选项。

此列的colModel:

{ name:'expires', 
    index:'7',
    width:90,
    align:"right",
    resizable: false,
    formatter: expireFormat,
    formatoptions: {srcformat:"l, F d, Y g:i:s A",newformat:"n/j/Y"}
},

我正在尝试做的一个例子

function expireFormat(cellValue, opts, rowObject) {
    if (cellValue == null || cellValue == 1451520000) {
        // a specific date that should show as blank
        return '';
    } else {
        // here is where I'd like to just call the $.fmatter.util.DateFormat
        var dt = new Date(cellValue * 1000);
        var op = $.extend({},opts.date);
        if(!isUndefined(opts.colModel.formatoptions)) {
            op = $.extend({},op,opts.colModel.formatoptions);
        }
        return $.fmatter.util.DateFormat(op.srcformat,dt,op.newformat,op);
    }
}

(在该DateFormat方法的内容中抛出一个异常,看起来就像它试图读入传入的选项的mask属性一样)

修改

将所有内容放在所需位置的$ .extend是从i18n库设置它的全局属性中获取它, $。jgrid.formatter.date

var op = $.extend({}, $.jgrid.formatter.date);
if(!isUndefined(opts.colModel.formatoptions)) {
    op = $.extend({}, op, opts.colModel.formatoptions);
}
return $.fmatter.util.DateFormat(op.srcformat,dt.toLocaleString(),op.newformat,op);

1 个答案:

答案 0 :(得分:4)

在jqGrid源代码中,当内置函数与使用自定义格式化程序时,不同的选项会传递给格式化程序:

    formatter = function (rowId, cellval , colpos, rwdat, _act){
        var cm = ts.p.colModel[colpos],v;
        if(typeof cm.formatter !== 'undefined') {
            var opts= {rowId: rowId, colModel:cm, gid:ts.p.id };
            if($.isFunction( cm.formatter ) ) {
                v = cm.formatter.call(ts,cellval,opts,rwdat,_act);
            } else if($.fmatter){
                v = $.fn.fmatter(cm.formatter, cellval,opts, rwdat, _act);
            } else {
                v = cellVal(cellval);
            }
        } else {
            v = cellVal(cellval);
        }
        return v;
    },

所以基本上发生的事情是当使用内置格式化程序时,cm.formatter作为参数传递。我需要确认这一点,但根据您收到的错误,这似乎是grid.locale-en.js中formatter选项的副本(或您正在使用的任何版本的i18n文件)。因此,当在内部调用时,格式化程序将包含其他选项,例如masks - 这是您的代码失败的选项。

作为预防措施,我会尝试将masks添加到您的op变量中。如果这样可以很好地解决您的问题,那么请继续将其他缺少的选项添加回代码,直到它正常工作。

这有帮助吗?