重用javascript代码(减少重复代码)

时间:2010-10-10 12:24:16

标签: extjs code-reuse extend

当我在网页上制作一些组件时,我发现有很多重复的代码,例如,在我的页面中我想制作两个图表。

它们最大的区别在于数据存储和标题,但它们具有许多相同的属性。

我这样做是通过定义一个新的Ext.chart实例:

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

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

config1和config2中有很多相同的内容,有什么想法可以避免这种情况吗?

顺便说一下,我认为扩展机制在ext中,但我无法获得有关如何仅使用ext3.2 API的更多细节。

1 个答案:

答案 0 :(得分:1)

您可以扩展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);

如果你想要它更短:

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"
});

编辑:使用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({ ... });
});
相关问题