Search code examples
extjsextjs4reusability

Reusablity in Ext JS 4


I have a lot of reusable code in my project (Some GUIs, grids, etc.). Does Extjs 4 provide any functionality for handling reusable code? Example: Java has the functionality for libraries that can be imported into any project.


Solution

  • ExtJs offers a high level of reusability if you know its core well.

    These various concepts come to mind:

    The Class System

    One of the most powerful features of ExtJs is that everything is organised into a class hierarchy, so essentially the design philosophy is similar to that in JAVA or C++.

    For instance, consider that your grids never show headers. You would write:

    Ext.define('HeadlessGrid', {
        extend: 'Ext.grid.Panel',
    
        hideHeaders: true,
    });
    

    So HeadlessGrid inherits from Ext.grid.Panel and just modifies its hideHeaders config. You can alter many other config of a component, but also its behaviour which is done by overriding its methods.

    Sometimes, instead of subclassing Ext classes, you want the Ext classes themselves to change.

    So something like this:

    Ext.override( Ext.grid.Panel, {
        hideHeaders: true,
    });
    

    Means that all grid component will not show headers by default.

    Namespaces

    The concept of 'library' can be achieved using namespaces. So to carry on with the previous example, you might have:

    Ext.define('Ext.Juice.HeadlessGrid', {
        extend: 'Ext.grid.Panel',
    
        hideHeaders: true,
    });
    

    Now HeadlessGrid belongs to the Ext.Juice namespace.

    You can set your class loader like so:

    Ext.Loader.setPath('Ext.Juice', '../../libs/Juice');    
    

    And now any classes under that folder are reusable by any application you write.

    Plugins

    Plugins allow you to extend (visible) component by means of composition instead of inheritance. So adding this plugin to any grid will hide the headers:

    Ext.define("Ext.plugin.Decapitator", {
        extend   : "Ext.AbstractPlugin",
        alias    : "plugin.decapitator",
    
        init : function( aPanel ) { 
            aPanel.hideHeaders = true;
        },
    
    });
    

    Mixins

    Mixins allow you to mix classes together, very much like multiple inheritance.

    The following code (from the docs) mixes the CanSing class with a Musician class.

    Ext.define('CanSing', {
         sing: function() {
             alert("I'm on the highway to hell...")
         }
    });
    
    Ext.define('Musician', {
         mixins: ['CanSing']
    })