提问者:小点点

优化jqgrid中动态创建的colmodel


我正在研究动态绑定的jqgrid。我已获得所需的输出。但是我写了一个很大的代码,它影响了我的性能,并且不可读。

我需要有人谁可以研究这一点,并优化我的代码简单。

提前谢谢。

我在这里复制了我的工作代码

 $.each($.parseJSON(columnsData).Table1, function () {
            // debugger;
            //Push the column name.
            colHeader.push(this.Name);

            //Check the datatype of the column.
            switch (this.Datatype) {

                case 'number':
                    if (this.DefaultValue != null && this.DefaultValue != "") {
                        //  debugger;
                        colname.push({
                            name: this.Name, index: this.Name, width: 100, align: 'left', formatter: 'number', sortable: true, editable: false, sorttype: 'int', hidden: JSON.parse(this.IsHidden), editoptions: {
                                defaultValue: this.DefaultValue
                            }, editrules: { required: JSON.parse(this.IsRequired) }

                        });
                    }
                    else {
                        colname.push({
                            name: this.Name, index: this.Name, width: 100, align: 'left', formatter: 'number', sortable: true, editable: false, sorttype: 'int', hidden: JSON.parse(this.IsHidden), editrules: { required: JSON.parse(this.IsRequired) }
                        });
                    }
                    lastFieldName = this.Name.toString(); //Store the fieldName.
                    break;
                case 'DateTime':
                    if (this.DefaultValue != null && this.DefaultValue != "") {
                        //If datetime then enable datepicker in the filter and edit form.
                        colname.push({
                            name: this.Name, search: true, index: this.Name, width: 100, stype: "text", editable: true, hidden: JSON.parse(this.IsHidden), searchoptions: {

                                dataInit: function (el) {

                                    $(el).datepicker({
                                        dateFormat: 'm/d/yy', maxDate: 0, changeMonth: true, changeYear: true, onSelect: function (dateText, inst) {
                                            setTimeout(function () {
                                                $('#TransactionsGrid')[0].triggerToolbar();
                                            }, 50);
                                        }
                                    });

                                }
                            }, editoptions: {

                                dataInit: function (el) {

                                    $(el).datepicker({
                                        dateFormat: 'm/d/yy', maxDate: 0, changeMonth: true, changeYear: true
                                    });

                                }, defaultValue: this.DefaultValue, readonly: 'readonly'
                            }, editrules: { required: JSON.parse(this.IsRequired) }
                        });
                    }
                    else {
                        colname.push({
                            name: this.Name, search: true, index: this.Name, width: 100, stype: "text", editable: true, hidden: JSON.parse(this.IsHidden), searchoptions: {

                                dataInit: function (el) {

                                    $(el).datepicker({
                                        dateFormat: 'm/d/yy', maxDate: 0, changeMonth: true, changeYear: true, onSelect: function (dateText, inst) {
                                            setTimeout(function () {
                                                $('#TransactionsGrid')[0].triggerToolbar();
                                            }, 50);
                                        }
                                    });

                                }
                            }, editoptions: {

                                dataInit: function (el) {

                                    $(el).datepicker({
                                        dateFormat: 'm/d/yy', maxDate: 0, changeMonth: true, changeYear: true
                                    });

                                }
                            }, editrules: { required: JSON.parse(this.IsRequired) }
                        });
                    }
                    lastFieldName = this.Name.toString();
                    break;
                case 'dropdown':
                    if (this.DefaultValue != null && this.DefaultValue != "") {
                        //   debugger;
                        if (this.ValueType == "F") {
                            colname.push({

                                name: this.Name, index: this.Name, width: 100, edittype: "select", editable: true, hidden: JSON.parse(this.IsHidden),
                                //formatter: imageFormatter, unformat: imageUnFormat,

                                /*(Set tooltip of the gridcell)
                                cellattr: function (rowId, val, rawObject, cm, rdata) {
                                if (rawObject[cm.name + "_Title"] == "") {
                                return 'title="' + rawObject[cm.name] + '"';
                                }
                                else
                                return 'title="' + val + ' (' + rawObject[cm.name + "_Title"] + ')"';
                                },*/

                                //IF dropdown then bind the values during edit form.
                                editoptions: { value: ':Select;' + this.ValueList.slice(0, -1), defaultValue: this.DefaultValue }, editrules: { required: JSON.parse(this.IsRequired) }, stype: 'select'
                                            , searchoptions: { value: ':All;' + this.ValueList.slice(0, -1) }, align: 'left', sortable: true

                            });
                        }
                        else {
                            colname.push({

                                name: this.Name, index: this.Name, width: 100, edittype: "select", label: this.ValueId, hidden: JSON.parse(this.IsHidden),


                                //IF dropdown then bind the values during edit form.
                                editoptions: { value: ':Select;' + this.ValueList.slice(0, -1), defaultValue: this.DefaultValue }, editrules: { required: JSON.parse(this.IsRequired) }, stype: 'select'
                                           , searchoptions: { value: ':All;' + this.ValueList.slice(0, -1) }, align: 'left', sortable: true

                            });
                        }
                    }
                    else {
                        if (this.ValueType == "F") {
                            colname.push({

                                name: this.Name, index: this.Name, width: 100, edittype: "select", editable: true, hidden: JSON.parse(this.IsHidden),

                                //IF dropdown then bind the values during edit form.
                                editoptions: { value: ':Select;' + this.ValueList.slice(0, -1) }, editrules: { required: JSON.parse(this.IsRequired) }, stype: 'select'
                                            , searchoptions: { value: ':All;' + this.ValueList.slice(0, -1) }, align: 'left', sortable: true

                            });
                        }
                        else {
                            colname.push({

                                name: this.Name, index: this.Name, width: 100, edittype: "select", label: this.ValueId, hidden: JSON.parse(this.IsHidden),


                                //IF dropdown then bind the values during edit form.
                                editoptions: { value: ':Select;' + this.ValueList.slice(0, -1) }, editrules: { required: JSON.parse(this.IsRequired) }, stype: 'select'
                                           , searchoptions: { value: ':All;' + this.ValueList.slice(0, -1) }, align: 'left', sortable: true

                            });
                        }
                    }
                    break;
                default:
                    if (this.DefaultValue != null && this.DefaultValue != "") {
                        colname.push({
                            name: this.Name, index: this.Name, width: 100, align: 'left', sortable: true, editable: true, hidden: JSON.parse(this.IsHidden), editrules: { required: JSON.parse(this.IsRequired) }
                        });
                    }
                    else {
                        colname.push({
                            name: this.Name, index: this.Name, width: 100, align: 'left', sortable: true, editable: true, hidden: JSON.parse(this.IsHidden), editrules: { required: JSON.parse(this.IsRequired) }
                        });
                    }
                    break;
            }


        });

jQuery("#TransactionsGrid").jqGrid({
    data: $.parseJSON(gridData).BuildTransactionsDataTable,
    datatype: "local",
    hoverrows: false,
    colNames: colHeader,
    colModel: colname,
    id: 'TransactionId',
    rowNum: 10,
    rownumbers: true,
    sortname: '_id',
    viewrecords: true,
    sortorder: 'desc',
    caption: "Transaction Details",
    height: '250px',
    gridview: true,
    ignoreCase: true

});

由于代码太大,无法查看,因此我进行了修改。请调查一下

更新:

我必须在控制器中处理的情况以及在客户端(this.DataType)中使用相同的情况下,代码将是一个大问题。

//代码:

case FieldStyleModel.FieldType.Date:
case FieldStyleModel.FieldType.DropDownCalendar:
case FieldStyleModel.FieldType.DateWithoutDropDown:
case FieldStyleModel.FieldType.DateWithSpin:
    drColumnDetails["Datatype"] = "date";
    break;
case FieldStyleModel.FieldType.DateTime:
case FieldStyleModel.FieldType.DateTimeWithoutDropDown:
case FieldStyleModel.FieldType.DateTimeWithSpin:
    drColumnDetails["Datatype"] = "datetime";
    break;
case FieldStyleModel.FieldType.DropDown:
case FieldStyleModel.FieldType.DropDownList:
case FieldStyleModel.FieldType.DropDownValidate:
    drColumnDetails["Datatype"] = "dropdown";
    break;
case FieldStyleModel.FieldType.URL:
    drColumnDetails["Datatype"] = "hyperlink";
    break;
case FieldStyleModel.FieldType.IntegerNonNegative:
case FieldStyleModel.FieldType.IntegerNonNegativeWithSpin:
case FieldStyleModel.FieldType.IntegerPositive:
case FieldStyleModel.FieldType.IntegerPositiveWithSpin:
    drColumnDetails["Datatype"] = "number";
    break;
case FieldStyleModel.FieldType.Integer:
case FieldStyleModel.FieldType.IntegerWithSpin:
    drColumnDetails["Datatype"] = "integer";
    break;
case FieldStyleModel.FieldType.Time:
case FieldStyleModel.FieldType.TimeWithSpin:
case FieldStyleModel.FieldType.TimeZone:
    drColumnDetails["Datatype"] = "Time";
    break;
case FieldStyleModel.FieldType.CheckBox:
    drColumnDetails["Datatype"] = "checkbox";
    break;
default:
    drColumnDetails["Datatype"] = "string";
    break;

共1个答案

匿名用户

小常见备注:

  • 参数的值高度可以是一个数字,如高度:250或字符串自动或100%。值'250px'不正确。我最喜欢的高度值是自动。
  • 您应该删除jqGrid的未知id选项(请参阅代码中的id:'TransactionId')。
  • sortname:'_id'是可疑的。您真的在输入数据的每个项目中都有_id属性吗?
  • 如果输入数据$. parseJSON(gridData)。BuildTransactionsDataTable只包含应该解释为文本的数据,而不是超文本标记语言片段,那么我建议您使用jqGrid的autoencode: true选项,

如果你在网格中加载成千上万行数据,那么答案中描述的技巧可以提高网格中数据加载的性能。你只需要做两个步骤:

  1. 删除网格的sortnamesortorder选项。对大型数据集进行排序可能需要时间。不sortname(或sortname:“)表示显示未排序的数据。它将提高数据初始加载的性能
  2. 删除网格的data选项,并将其设置在onInitGrid回调中:
$("#TransactionsGrid").jqGrid({
    datatype: "local",
    hoverrows: false,
    colNames: colHeader,
    colModel: colname,
    rowNum: 10,
    rownumbers: true,
    viewrecords: true,
    caption: "Transaction Details",
    height: "auto",
    gridview: true,
    autoencode: true,
    ignoreCase: true,
    onInitGrid: function () {
        // get reference to parameters
        var p = $(this).jqGrid("getGridParam");

        // set data parameter
        p.data = $.parseJSON(gridData).BuildTransactionsDataTable;
    }
});

答案中的演示加载90000行数据,加载时间约为52-130毫秒,具体取决于我使用的web浏览器。在我看来,这是一段美好的时光。如果没有这个技巧(参见演示),数据加载大约需要1600-11000毫秒。如果添加数据排序(参见另一个演示),那么我得到的时间是2100-29000毫秒。

更新:首先,您应该从JavaScript代码中删除所有不需要的东西。

  • 索引属性必须与名称属性的值相同。如果删除索引属性,jqGrid内部将创建正确的索引值。因此,我严格建议不要在colModel中指定index属性

因此,我将您的代码修改为以下内容:http://jsfiddle.net/z1ujyh02/6/.我下面包含的代码中最重要的部分:

var columnsData = "...", gridData = "...";
var mydata = $.parseJSON(gridData).BuildTransactionsDataTable, existingProperties = {},
    numberTemplate = {formatter: 'number', sorttype: 'int'},
    dateTemplate = {
        editable: true,
        searchoptions: {
            dataInit: function (el) {
                var self = this;
                $(el).datepicker({
                    dateFormat: 'm/d/yy', maxDate: 0, changeMonth: true, changeYear: true,
                    onSelect: function (dateText, inst) {
                        setTimeout(function () {
                            self.triggerToolbar();
                        }, 50);
                    }
                });
            }
        },
        editoptions: {
            dataInit: function (el) {
                $(el).datepicker({
                    dateFormat: 'm/d/yy', maxDate: 0, changeMonth: true, changeYear: true
                });
            },
            readonly: 'readonly'
        }
    }
    dropdownTemplate = {
        edittype: "select",
        editable: true,
        stype: "select"
    };

$.each(mydata, function () {
    var p;
    for (p in this) {
        if (this.hasOwnProperty(p) && this[p] !== null && (typeof this[p] === "string" && $.trim(this[p]) !== "")) {
            existingProperties[p] = true;
        }
    }
});

var colname = [{ name: "TransactionId", sorttype: "int", key: true }];
//Loop into the column values collection and push into the array.
$.each($.parseJSON(columnsData).Table1, function () {
    //Check the datatype of the column.
    var cm = {
            name: this.Name,
            hidden: JSON.parse(this.IsHidden) || !existingProperties.hasOwnProperty(this.Name),
            editoptions: this.DefaultValue != null && this.DefaultValue != "" ? { defaultValue: this.DefaultValue } : {},
            editrules: { required: JSON.parse(this.IsRequired) }
        };
    switch (this.Datatype) {
        case 'number':
            $.extend(true, cm, { template: numberTemplate });
            lastFieldName = cm.name; //Store the fieldName.
            break;
        case 'DateTime':
            $.extend(true, cm, { template: dateTemplate });
            lastFieldName = cm.name;
            break;
        case 'dropdown':
            var values = this.ValueList.slice(0, -1);
            $.extend(true, cm, {
                template: dropdownTemplate,
                editoptions: { value: ":Select;" + values, defaultValue: this.DefaultValue },
                searchoptions: { value: ":All;" + values }
            },
            this.ValueType == "F" ? { label: this.ValueId } : {} );
            break;
        default:
            break;
    }
    if (cm)
    colname.push(cm);
});

//Binding grid Starts.
$("#TransactionsGrid").jqGrid({
    //data: mydata,
    datatype: "local",
    hoverrows: false,
    colModel: colname,
    rowNum: 10,
    rownumbers: true,
    pager: "#TransactionsPager",
    localReader: { id: "TransactionId" },
    prmNames: { id: "TransactionId" },
    viewrecords: true,
    caption: "Transaction Details",
    height: "auto",
    gridview: true,
    autoencode: true,
    ignoreCase: true,
    cmTemplate: { width: 100 },
    onInitGrid: function () {
        // get reference to parameters
        var p = $(this).jqGrid("getGridParam");

        // set data parameter
        p.data = mydata;
    }
});