Search code examples
javascriptjqueryasp.net-mvcmodel-view-controllerdevextreme

Create a generic variable for a grid to reuse the configuration in each grid


I'm using DevExpress' DevExtreme controls, more specifically the DxDataGrid.

Right now, every time I use a DxDataGrid I need to specify the configuration like this:

var grid = $("#myGrid").dxDataGrid({
    // These options need to be specified for each DxDataGrid
    dataSource: {
        ...
    },
    columns: [
        ...                
    ],
    editing: {
        ...                
    },
    // The following options are always the same for every DxDataGrid
    columnChooser: {
        enabled: true
    },
    allowColumnReordering: true,
    sorting: {
        mode: 'multiple'
    },
    groupPanel: {
        visible: true,
        emptyPanelText: 'Blabla'
    },
    pager: {
        visible: true,
        showNavigationButtons: true,
        showInfo: true,
        showPageSizeSelector: true,
        allowedPageSizes: [10, 20, 50, 100]
    },
    paging: {
        pageSize: 10
    },
    filterRow: {
        visible: true
    },
    searchPanel: {
        visible: true,
        placeholder: 'Buscar'
    },
}).dxDataGrid('instance');

I'd like to avoid duplicating code for all the config parameters that are identical for each DxDataGrid. In the following question a DevExpress support member explained that:

The data grid configuration is a regular JavaScript object. You can create an object variable with the default grid configuration and use it for each grid. Use the jQuery.extend() function to add new options/properties to your default configure object when necessary.

I have no idea how to do this and there are no code samples available. Any help?


Solution

  • Create an external file that contains a global variable for you common options, for example

    var commonOptions = { 
        columnChooser: {
            enabled: true
        },
        allowColumnReordering: true,
        ....
    };
    

    and in the view

    <script src="~/Scripts/DxDataGridCommonOptions.js"></script> // load the common options into the view
    var viewOptions = { 
        dataSource: {
        .... // your view specific options
        },
        ....
    };
    var grid = $("#myGrid").dxDataGrid(
        $.extend(commonOptions, viewOptions) // merge the 2 sets of options
    ).dxDataGrid('instance');