封装扩展Kendo UI Grid

封装后的代码如下:

$(function () {
    function KendoGrid() {
        this.gridOptions = {
            height: "100%",
            sortable: true,
            reorderable: true,
            scrollable: true,
            filterable: {
                mode: "menu",
                extra: false,
                operators: {
                    string: {
                        contains: "Contains",
                        equal: "Equals to"
                    }
                }
            },
            editable: { mode: "popup" },
            resizable: true,
            columnMenu: true,
            pageable: {
                refresh: true,
                pageSizes: true,
                buttonCount: 5
            },
            dataSourceOptions: {
                transport: {},
                batch: true,
                pageSize: 50,
                schema: {
                    data: function (d) {
                        return d.Data;
                    },
                    total: function (d) {
                        return d.RowCount;
                    }
                },
                serverPaging: true,
                serverFiltering: true,
                serverSorting: true
            }
        };
        this.init = function (options) {
            var thatOptions = options;
            var self = this;

            this.setOptions(options);

            // render KendoUI Grid
            $("#" + options.id).kendoGrid(self.gridOptions);

            $("#" + options.id + " .k-grid-create").off("click").on("click", function (e) {
                e.preventDefault();
                if (thatOptions.dialogOptions) {
                    $.dialog.showDialog({
                        id: thatOptions.dialogOptions.id,
                        title: thatOptions.dialogOptions.title,
                        content: thatOptions.gridRowCreateUrl,
                        showSave: true,
                        callbackAfterSaving: function () {
                            if (thatOptions.dialogOptions.callbackAfterSaving) {
                                thatOptions.dialogOptions.callbackAfterSaving();
                            }
                        }
                    });
                }
            });
        };
        this.setDataSource = function (options) {
            if (options.dataSourceOptions) {
                var thatOptions = options;
                this.gridOptions.dataSourceOptions.transport = {
                    read: {
                        type: "post",
                        url: options.dataSourceOptions.url,
                        dataType: "json",
                        contentType: "application/json"
                    },
                    parameterMap: function (options, operation) {
                        if (operation === "read") {
                            var criterias = {
                                Limit: options.take || 50,
                                Offset: options.skip || 0
                            };
                            if (options.filter && options.filter.filters) {
                                criterias.Filters = options.filter.filters;
                            }

                            if (options.sort && options.sort.length > 0) {
                                criterias.SortBy = options.sort[0].field;
                                criterias.SortDirection = options.sort[0].dir + "ending";
                            }

                            // Apply custom parameterMap logic
                            var customParamMap = thatOptions.dataSourceOptions.customParamMap;
                            if (customParamMap) {
                                criterias = customParamMap(criterias);
                            }
                            return kendo.stringify(criterias);
                        }
                    }
                };
            }
            this.gridOptions.dataSource = new kendo.data.DataSource(this.gridOptions.dataSourceOptions);
        };
        this.setOptions = function (options) {
            var self = this;

            //Only assign the property values the keys of which are included in ‘gridOptions‘
            for (var property in options) {
                if (this.gridOptions.hasOwnProperty(property) && property != "dataSourceOptions") {
                    this.gridOptions[property] = options[property];
                }
            }

            this.gridOptions.temp = options; // used temporary

            // Append each item to toolbar container
            if (options.toolbar) {
                this.setToolbar(options);
            }

            this.setDataSource(options);

            //Fetch columns data from server
            if (!options.columns) {
                $.ajax({
                    type: "post",
                    url: options.gridColumnsUrl,
                    data: options.gridColumnsParams || {},
                    dataType: "json",
                    async: false,
                    success: function (data) {
                        options.columns = data;
                    }
                });
            }
            this.gridOptions.columns = options.columns;

            if (options.showCheckBox) {
                this.gridOptions.columns.unshift({
                    headerTemplate: ‘<input type="checkbox" />‘,
                    template: ‘<input type="checkbox" />‘,
                    width: 35
                });
            }
            if (!options.dataBound) {
                this.gridOptions.dataBound = function () {
                    if (options.gridRowDblClickEnabled) {
                        self.gridRowDblClick();
                    }

                    if (options.gridRowContextMenuEnabled) {
                        self.gridRowContextMenuClick();
                    }

                    if (options.showCheckBox) {
                        self.checkAll();
                    }
                };
            }
        };
        this.setToolbar = function (options) {
            var toolbar = [];
            $(options.toolbar).each(function (index, toolItem) {
                switch (toolItem.name) {
                    case "addRecord":
                        toolbar.push({ template: "<a role=‘button‘ class=‘k-button k-button-icontext k-grid-create‘ href=‘javascript:void(0);‘><span class=‘k-icon k-i-plus‘></span>" + toolItem.text + "</a>" });
                        break;
                    case "importExcel":
                        toolbar.push({ template: "<a role=‘button‘ class=‘k-button k-button-icontext k-grid-import‘ href=‘javascript:void(0);‘><span class=‘k-icon k-i-upload‘></span>" + toolItem.text + "</a>" });
                        break;
                    case "excel":
                        toolbar.push({ name: "excel", text: "Export to Excel" });
                        options.excel = {
                            fileName: "Export.xlsx",
                            proxyURL: "/GridView/ExportExcel",
                            filterable: true
                        };
                        break;
                    case "pdf":
                        toolbar.push({ name: "pdf", text: "Export to PDF" });
                        options.pdf = {
                            allPages: true,
                            avoidLinks: true,
                            paperSize: "A4",
                            margin: { top: "2cm", left: "1cm", right: "1cm", bottom: "1cm" },
                            landscape: true,
                            repeatHeaders: true,
                            template: ‘<div class="page-template">‘ +
                            ‘< div class="header" >‘ + ‘<div style="float: right">Page #: pageNum # of #: totalPages #</div>‘ +
                            ‘</div>‘ +
                            ‘<div class="watermark">M+W Group</div>‘ +
                            ‘<div class="footer">Page #: pageNum # of #: totalPages #</div>‘ +
                            ‘</div>‘,
                            scale: 0.8
                        };
                        break;
                    default: break;
                }
            });
            this.gridOptions.toolbar = toolbar;
        };
        this.gridRowDblClick = function () {
            var thatOptions = this.gridOptions.temp;
            $("#" + thatOptions.id + " tbody tr[role=row]").off("dblclick").on("dblclick", function (e) {
                e.preventDefault();
                var id = $("#" + thatOptions.id).data("kendoGrid").dataItem($(this)).Id;
                $.dialog.showDialog({
                    id: thatOptions.dialogOptions.id,
                    title: thatOptions.dialogOptions.title,
                    content: $.format("{0}{1}", thatOptions.gridRowEditUrl, id),
                    showSave: true,
                    callbackAfterSaving: function () {
                        if (thatOptions.dialogOptions.callbackAfterSaving) {
                            thatOptions.dialogOptions.callbackAfterSaving();
                        }
                    }
                });
            });
        };
        this.gridRowContextMenuClick = function () {
            var self = this;
            var thatOptions = this.gridOptions.temp;
            if (thatOptions.contextMenuOptions) {
                var menuItems = [
                    { name: "view", onClick: openEditView },
                    { name: "edit", onClick: openEditView },
                    {
                        name: "remove", onClick: function (e) {
                            var id = $("#" + thatOptions.id).data("kendoGrid").dataItem(e.target).Id;
                            kendo.confirm("Are you sure to proceed?").then(function () {
                                $.post(thatOptions.gridRowRemoveUrl + id, function (d) {
                                    if (d && d.Ok) {
                                        self.refresh();
                                    }
                                });
                            });
                        }
                    }];

                $(thatOptions.contextMenuOptions.items).each(function (index, item) {
                    for (var i = 0; i < menuItems.length; i++) {
                        if (menuItems[i].name == item.name) {
                            if (!item.onClick) {
                                item.onClick = menuItems[i].onClick;
                            }
                        }
                    }
                });

                function openEditView(e) {
                    var id = $("#" + thatOptions.id).data("kendoGrid").dataItem($(e.target)).Id;
                    var url = $.format("{0}{1}", thatOptions.gridRowEditUrl, id);
                    $.dialog.showDialog({
                        id: thatOptions.dialogOptions.id,
                        title: thatOptions.dialogOptions.title,
                        content: url,
                        showSave: true,
                        callbackAfterSaving: function () {
                            self.refresh();
                        }
                    });
                }
                $.contextMenu.init(thatOptions.contextMenuOptions);
            }
        };
        this.checkAll = function () {
            var thatOptions = this.gridOptions.temp;
            $("#" + thatOptions.id + " thead tr[role=row] th:first-child :checkbox").on("click", function () {
                var parentCheckBox = $(this);
                $("#" + thatOptions.id + " tbody tr[role=row] td:first-child :checkbox").each(function () {
                    $(this).prop("checked", $(parentCheckBox).prop("checked"));
                });
            });

            $("#" + thatOptions.id + " tbody tr[role=row] td:first-child :checkbox").on("click", function () {
                var parentCheckBox = $("#" + thatOptions.id + " thead tr[role=row] th:first-child :checkbox");
                if ($("#" + thatOptions.id + " tbody tr[role=row] td:first-child :checked").size() != $("#" + thatOptions.id + " tbody tr[role=row] td:first-child :checkbox").size()) {
                    parentCheckBox.prop("checked", false);
                } else {
                    parentCheckBox.prop("checked", true);
                }
            });
        };
        this.refresh = function () {
            var self = this;
            var thatOptions = this.gridOptions.temp;
            $("#" + thatOptions.id).data("kendoGrid").dataSource.read();
            setInterval(function () {
                if (thatOptions.gridRowDblClickEnabled) {
                    self.gridRowDblClick();
                }

                if (thatOptions.gridRowContextMenuEnabled) {
                    self.gridRowContextMenuClick();
                }

                if (thatOptions.showCheckBox) {
                    self.checkAll();
                }
            }, 50);
        };
    };
    $.kendoGrid = $.kendoGrid || {};

    $.extend($.kendoGrid, {
        init: function (options) {
            var grid = new KendoGrid();
            grid.init(options);
        }
    });
});

使用场景:

 <div id="gridDeliverables"
                     data-role="custom_grid"
                     data-toolbar=‘[{ "name": "addRecord", "text": "Add Record" },
                                 { "name": "importExcel", "text": "Import from Excel" },
                                 { "name": "excel", "text": "Export to Excel" },
                                 { "name": "pdf", "text": "Export to PDF" }]‘
                     data-dialog-Options=‘{"id": "PackageDeliverableDialog","title": "Deliverable"}‘
                     data-sortable="true"
                     data-reorderable="true"
                     data-filterable="false"
                     data-column-Menu="false"
                     data-height=""
                     data-url="@Url.Action("GetDataSource", "GridView")"
                     data-filters=‘[{ "Field": "PrimaryPackageId", "Value": "@Model.Id", "Operator": "Eq" }]‘
                     data-meta-Type="@MetaType.Deliverables"
                     data-grid-Columns-Url="@Url.Action("GetColumnHeaders", "GridView")"
                     data-grid-Columns-Params=‘{ "metaType": "@MetaType.Deliverables" }‘
                     data-grid-Row-Create-Url=‘@Url.Action("Create", "DesignDeliverable")‘>
                </div>

全局触发处理:

  $(".dialog [data-role=custom_grid]").each(function () {// Render cunstom grid by hand
            var self = $(this);
            setTimeout(function () {
                if (!self.data("kendoGrid") && !self.data("rendercompleted")) {
                    var options = self.data();
                    options.id = self.prop("id");
                    options.dataSourceOptions = {
                        url: options.url,
                        customParamMap: function (criterias) {
                            criterias.Filters = options.filters || [];
                            criterias.MetaType = options.metaType;
                            return criterias;
                        }
                    };
                    $.kendoGrid.init(options);
                    self.data("rendercompleted", true);
                }
            }, 1000);
        });
时间: 2024-10-10 23:43:11

封装扩展Kendo UI Grid的相关文章

Kendo UI Grid 模型绑定

开篇 接触 Asp.net MVC 时间较长的童鞋可能都会了解过模型绑定(Model Binding),而且在一些做 Web 项目的公司或是Team面试中也经常会被问到.项目中有很多 Action 中都使用了自定义的模型绑定,但是业务逻辑太过复杂不适合做为例子与大家分享,而今天在做一个 Kendo UI 的功能时觉得可以用 Kendo UI 做为例子与大家分享与探讨一个典型的 Model Binding 的过程. 写的比较随性,欢迎大家讨论及拍砖! 背景介绍 Kendo UI: 它是一个非常出名

Kendo UI:Grid中单元格日期格式化

摘自: http://blog.csdn.net/sun_jy2011/article/details/41546337 Kendo UI:Grid中怎么格式化时间类型数据? 解决方案 (1)使用format格式化 { field: "updateTime", title: "更新时间", width: 200, format: "{0: yyyy-MM-dd HH:mm:ss}" } (2)使用template实现 { field: "

kendo ui grid 创建一行数据多次添加(kendo ui grid datasource multiple create)

今天测试之前使用kendo ui grid 做的数据表格的时候发现了一个bug,我使用的是kendo ui grid 系统自带的自动添加数据和编辑数据的功能,每次添加完一条数据的时候继续添加的时候会发现之前添加的数据会重复添加.查看官方文档,文档说是dataSource schema model id 必须是唯一键,而且添加数据完成之后需要返回一个数据包含id,结果研究了半天没有找到问题所在. var crudServiceBaseUrl = "/NFC"; var dataSourc

Kendo UI grid 表格数据更新

1.整行数据更新 ? 1 2 3 4 5 //获取grid表格<br>var table0 = $(updateTableID).data("kendoGrid");<br>//删除第一条 var lastTableData = table0.dataSource.at(0); table0.dataSource.remove(lastTableData); //添加一条至最后一条后 table0.dataSource.add(req[k]);<br>

kendo ui grid 汉化

加入js引用 <link href="http://cdn.kendostatic.com/2014.2.716/styles/kendo.common.min.css" rel="stylesheet" /> <link href="http://cdn.kendostatic.com/2014.2.716/styles/kendo.default.min.css" rel="stylesheet" /&g

AngularJS +Kendo UI Grid template

var dataSource = new kendo.data.DataSource({ transport: { dataType: "json", read: inputUri + $stateParams.subjectID, }, pageSize: 10, }); $scope.mainGridOptions = { dataSource: dataSource, //height: 420, scrollable: false, sortable: true, filter

Kendo UI:Grid中单元格样式控制

问题 Grid某个单元格的样式怎么设置? 解决方案 使用attributes属性设置,如果有css中class属性,需要加双引号"".如 { field: "name", title: "Name", attributes: { "class": "table-cell", style: "text-align: right; font-size: 14px" } }

Kendo UI:Grid中标题css样式设置

问题 Grid表格的标题样式怎么设置? 解决方案 使用headerAttributes属性设置,如果有css中class属性,需要加双引号"".如 { field: "name", headerAttributes: { "class": "table-header-cell", style: "text-align: right; font-size: 14px" } }

kendo ui 好用的小部件--grid

Kendo Ui Grid控件,继承至Widget. https://demos.telerik.com/kendo-ui/grid/index  快速上手教程  下面的代码来自本教程 做表格时非常方便,具有非常强大的功能: <div id="grid"></div> <script> $(document).ready(function () { $("#grid").kendoGrid({ dataSource: { //数据