serg
serg

Reputation: 111275

What are some good approaches for reusing parts of a config?

I have several grids that share common columns for example (the issue is not limited to columns, any config object). Currently I'm doing something like this:

//columns.js
var columns = {"reusable1": {...}, "reusable2": {...}};

//grid views
Ext.define('MyApp.view.Grid', {
    columns: [
        {text:'inline column1'},
        columns.reusable1,
        columns.reusable2,
        {text:'inline column2'},
    ]
});

This gets the job done, but what would be the better approach that works in a similar way (without creating unique xtype for each config piece, or modifying configs in a constructor or initComponent). I just want to be able to put misc reusable config pieces inline as before.

Upvotes: 3

Views: 87

Answers (2)

Emissary
Emissary

Reputation: 10148

I think most other options will likely reduce readability or just look outright convoluted - but you could override the base class and include a configuration for "named" columns instead.

I'm assuming when you say, "not modifying configs in a constructor" you are referring to the grid/s implementing the columns rather than similar logic that could be tidied away somewhere else.

Ext.define('App.override.grid.column.Column', {
    override: 'Ext.grid.column.Column',

    config: {
        name: null    
    },

    statics: {
        namedColumns: {
            reusable1: { /* ... */ },
            reusable2: { /* ... */ },
            // ...
        }
    },

    constructor: function(args){
        var _args = args || {},
            statics = Ext.grid.column.Column,
            defaults = statics.namedColumns[_args.name] || {};
        this.callParent([Ext.apply({}, _args, defaults)]);
    }
});

Usage

Ext.define('App.view.Grid', {
    columns: [
        { text: 'inline column1' },
        { name: 'reusable1'      },
        { name: 'reusable2'      },
        { text: 'inline column2' },
    ]
});

Advantages

  • Tidied away within the project structure rather than existing in the global scope.
  • Avoids potential dependency issues as Sencha CMD will ensure the override (and by extension these defaults) exist before any grid is declared.
  • The named configurations are more flexible and may be neatly overridden inline.
    e.g. { name: 'reusable', flex: 2 /* superseding value */ }

Disadvantages

  • The xtype can't be used as part of the default configuration, this would still need to be specified inline for anything other than a regular grid-column.
    e.g. { xtype: 'datecolumn', name: 'some-defaults' }

» Fiddle

Upvotes: 1

Robert Klein Kromhof
Robert Klein Kromhof

Reputation: 516

Take a look at these configs:

The defaults config works for the entire container, where as columns has its own defaults option.

Hope this helps!

Upvotes: 0

Related Questions