ExtJs 5.1: Change Super Class at runtime

234 views Asked by At

I have the following two classes which extend the ExtJs Grid panel:

  1. ReadonlyDataGrid - as name suggests, basic non-editable ExtJs grid
  2. EditableDataGrid - ExtJs grid with cell & row editing plugin

Now I want to provide a new class which will extend one of the above 2 classes based on a property set by the developer in the grid JSON configuration

For Eg:

Java:

parentObj.put("gridType", "readonly");

JS:

Ext.define('Grid.view.GridFactory', {
extend: 'Grid.view.AbstractGridFactory',
alias: 'widget.gridfactory',
singleton: true,
create : function(model){
    var grid;
    switch(model.input.gridType)
    {
        case 'readonly':
            grid = new Grid class extending the ReadonlyDataGrid class;
            break;
        case 'editable':
            grid = new Grid class extending the EditableDataGrid class;
            break;          
    }

    return grid;
  }
});

Right now I have to create two separate class files to handle this.

Class 1:

Ext.define('Grid.view.EditableGrid',{
extend : 'Grid.view.EditableDataGrid',
.... //additional features
});

Class 2:

Ext.define('Grid.view.ReadonlyGrid',{
extend : 'Grid.view.ReadOnlyDataGrid',
.... //additional features
});
  1. How can I merge these 2 classes into 1?
  2. How can I change the extend property or extend the correct class based on the user configuration as shown above?
  3. Design wise what is better? Having 1 class and changing the superClass at runtime or maintaining 2 classes but with redundant/same code?
1

There are 1 answers

6
Greendrake On
  1. By using mixins.
  2. Technically you can define classes at runtime and choose any extend property you see fit:
Ext.define('Grid.view.RuntimeGrid',{
    extend: 'Grid.view.' + (model.input.gridType === 'readonly' ? 'ReadonlyDataGrid' : 'EditableDataGrid'),
    //additional features
});

But that is bad practice.

  1. Changing the superClass at runtime is even worse. Designwise, there are two seemly options:

    • Have two classes, but Don't Repeat Yourself: put your "redundant/same" code into a mixin and include it in both classes; OR
    • Have just one class which can be editable when configured to be so. It would accept a configuration option say editable and will only instantiate the relevant editing plugins / editors when the option is true.