码迷,mamicode.com
首页 > 其他好文 > 详细

封装扩展Kendo UI Grid

时间:2017-04-20 23:57:59      阅读:433      评论:0      收藏:0      [点我收藏+]

标签:new   UI   span   record   contain   sel   logo   foo   ring   

封装后的代码如下:

$(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);
        });

 

封装扩展Kendo UI Grid

标签:new   UI   span   record   contain   sel   logo   foo   ring   

原文地址:http://www.cnblogs.com/kongdf/p/6741509.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!