简体   繁体   中英

How can I avoid code duplication when configuring widgets I build using JavaScript object literals?

I know there is probably some very small and simple inheritance or extension solution for this, but I hope this question will prove beneficial for more than just me. And quicker.

I have eg the following code to set up a Kendo UI grid . I need to repeat this code exactly for two grids on the same view, except for one parameter difference in the transport.read.data object. I realise I can factor out the model and columns definitions into shared objects, but I would like to share the whole grid config eventually. Maybe a jQuery extension called myUserKendoGrid ?

    $("#availableUsersGrid").kendoGrid({
        dataSource: {
            transport: {
                read: {
                    url: "/Role/AvailableUsersJson",
                    data: { roleId: $("#Id").val() },
                    type: "GET"
                }
            },
            schema: {
                model: {
                    id: "Id",
                    fields: {
                        Id: { editable: false },
                        UserName: { editable: false },
                        EmployeeRefNum: { editable: false },
                        EmployeeSurname: { editable: false },
                        EmployeeFullNames: { editable: false }
                    }
                }
            }
        },
        columns: [
                { field: "UserName", title: "User Name" },
                { field: "EmployeeRefNum", title: "Emp. No." },
                { field: "EmployeeSurname", title: "Surname" },
                { field: "EmployeeFullNames", title: "Name" }
        ],
        selectable: "multiple, row",
        editable: false,
        sortable: true,
        pageable: true
    });

You could simply clone your configuration via the .extend() method of jQuery . For example:

var superDuperAwesomeConfiguration = {
    // moar configs go here, yo!
};

var copyCatConfigs = jQuery.extend(true, {}, superDuperAwesomeConfiguration);

// modify copyCatConfigs properties here

$("#gridA").kendoGrid(superDuperAwesomeConfiguration);
$("#gridB").kendoGrid(copyCatConfigs);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM