Search code examples
extjscode-reuseextend

reuse javascript codes(reduce the Duplicate codes)


When I make some components in my web page,I found there a so many duplicate codes,for example,in my page I want to make two charts.

THe biggest difference of them is the data store and the title,however they have many same attributes.

I do this by define a new instance of Ext.chart:

var chart1=new Ext.chart.LineChart{config1};

var chart2=new Ext.chart.LineChart{config2};

There are so many same contents in the config1 and config2,is there any ideas to avoid this?

BTW,I have thought the extend mechanism in ext,however I can not get more details about how to use it only from the ext3.2 API.


Solution

  • You can extend config

    var config = {
        // do you shared config here
    }
    
    // and apply any different/extending configs here
    var config1 = Ext.apply(config, { title: "Title of config 1" }
    var config2 = Ext.apply(config, { title: "Title of config 2" }
    
    var chart1 = new Ext.chart.LineChart(config1);
    var chart2 = new Ext.chart.LineChart(config2);
    

    And if you want it even shorter:

    var chart1 = new Ext.chart.LineChart(Ext.apply(config, {
        title: "Title of config 1"
    });
    var chart2 = new Ext.chart.LineChart(Ext.apply(config, {
        title: "Title of config 2"
    });
    

    Edit: With Ext.extend:

    Ext.chart.LineChart = Ext.extend(Ext.chart.LineChart, {
        // put your shared config in here
    });
    
    var chart1 = new Ext.chart.LineChart({
        title: "Title of chart 1", 
        store: new Ext.data.Store({ ... });
    });
    var chart2 = new Ext.chart.LineChart({
        title: "Title of chart 2", 
        store: new Ext.data.Store({ ... });
    });