在使用extjs开发应用系统时,难免会出现一个js文件内包含数百行甚至上千行代码的情况,例如程序主界面或者复杂一点的界面,下面介绍如何通过自定义组件减少单个extjs javascript代码行数的方法。
下图中的主界面显示了两个统计图:
最初的时候统计图的js代码是写死在tagpanel里面的,通过extjs 自定义组件的方法拆分成单独的类文件以后的代码:
Ext.define('app.view.main.Main_Pie_Chart', {
extend: 'Ext.panel.Panel',
alias : 'widget.main_pie_chart',
chart_store:null,
layout: {
type: 'fit'
},
initComponent: function() {
var me = this;
Ext.applyIf(me, {
title:'库存商品成本分布饼图',
items:[
{
xtype:'chart',
//region: 'center',
animate: true,
width:450,
height:400,
store:me.chart_store,
shadow: true,
legend: {
position: 'right'
},
insetPadding: 60,
theme: 'Base:gradients',
series: [{
type: 'pie',
field: 'data1',
showInLegend: true,
donut: 35,
tips: {
trackMouse: true,
width: 140,
height: 28,
renderer: function(storeItem, item) {
//var total = 0;
//storeItem.each(function(rec) {
// total += rec.get('data1');
//});
//this.setTitle(storeItem.get('product_name') + ': ' + Math.round(storeItem.get('data1') / total * 100) + '%');
this.setTitle(storeItem.get('product_name') + ': ' +storeItem.get('data1')+'元库存成本');
}
},
highlight: {
segment: {
margin: 20
}
},
label: {
field: 'product_name',
display: 'rotate',
contrast: true,
font: '18px Arial'
}
}]
}
]
});
me.callParent(arguments);
}
});
上面的代码中定义了一个叫做“app.view.main.Main_Pie_Chart”的类,在tabpanel里面需要引用时需要借助requires导入,见下面的代码:
Ext.define('app.view.Viewport', { renderTo: Ext.getBody(), extend: 'Ext.container.Viewport', alias: 'widget.main_viewport', requires: [ 'Ext.tab.Panel', 'Ext.layout.container.Border', 'app.store.StockChartPieStore', 'app.view.main.Main_Top_Panel', 'app.view.main.Main_Pie_Chart', 'app.view.main.Main_Column_Chart' ], layout: { type: 'border' },
具体在主界面的tabpanel使用的代码就可以简化为:
{ xtype: 'tabpanel', region: "center", id: 'content_tabpanel', margins: '2 5 5 0', activeTab: 0, border: false, items: [{ id: 'start-panel', title: '欢迎使用', layout: 'hbox', bodyStyle: 'padding:25px; background-image: url(./img/bg.jpg); background-repeat: no-repeat; background-attachment: fixed; background-position: 100% 100%', items: [ { xtype: 'main_pie_chart', chart_store: chart_data_store } , { xtype: 'main_column_chart', chart_store: chart_data_store } ] }
注意这里面其实是引用了两个自定义的extjs 统计图组件类,两个图对应同一个store,所以在写完xtype去引用自定义组件后又提供了chart_store这个extjs自定义类属性。