当我定义 View 类时,我必须为子组件设置很多重复的配置。
这是一个例子:
Ext.define('TEST.view.transaction.TransactionEditor', {
extend: 'Ext.form.Panel',
...
items: [{
...
labelWidth:80,
width: 230,
tdAttrs: { style: 'padding: 10px 20px 10px 20px;' },
...
},{
...
labelWidth:80,
width: 230,
tdAttrs: { style: 'padding: 10px 20px 10px 20px;' }
...
},
...
],
...
}
正如你所看到的,labelWidth、width和style重复了好几次。我想使用一些常量或变量来代替这些魔数(Magic Number)。在 EXTJS 中执行此操作的正确方法是什么?
更新: 下面两种方法效果都不好。
使用默认值适用于 labelWidth 和 width,但不适用于 tdAttrs。
通过使用 initComponent 方法,组件停止显示。
initComponent:function() {
var tdAttrs = { style: 'padding: 10px 20px 10px 20px;' }; Ext.apply(this,{ items:[{ tdAttrs:tdAttrs }]} ); this.callParent(arguments); },
更新2:
我使用方法1解决了tdAttrs不起作用的问题。tdAttrs应该放在布局配置下而不是默认值下。我不知道为什么,但这是工作代码。
layout: {
type: 'table',
// The total column count must be specified here
columns: 4,
tdAttrs: { style: 'padding: 5px 10px 5px 10px;' }
},
defaults:{
labelWidth:70,
width: 210
},
items: [/* include child components here */
{
...
},
{
...
},
...
]
对于initComponent方法,我还是不知道怎么做。请帮忙。
最佳答案
有各种DRY (Don't Repeat Yourself) ExtJS 中的方法。
如果这些值在容器的所有个适用子项中重复,则可以使用 defaults
:
Ext.define('TEST.view.transaction.TransactionEditor', {
extend: 'Ext.form.Panel',
defaults:{
labelWidth:80,
width: 230,
tdAttrs: { style: 'padding: 10px 20px 10px 20px;' },
queryMode:'local' // EXAMPLE: this will be added to all fields, but only have effect in combos!
},
如果不是,您可以定义变量:
var labelWidth=80,
...
Ext.define('TEST.view.transaction.TransactionEditor', {
extend: 'Ext.form.Panel',
...
labelWidth:labelWidth,
但是这是不推荐的,因为这样你就会得到一堆困惑的全局变量。最好将整个项目定义放入 initComponent 中,因为这样变量就保留在作用域内:
Ext.define('TEST.view.transaction.TransactionEditor', {
extend: 'Ext.form.Panel',
initComponent:function() {
var labelWidth = 80,
width = 230;
Ext.apply(this,{
items:[{
...
labelWidth:labelWidth,
width: width,
...
},{
...
labelWidth:labelWidth,
width: width,
...
},
...
],
...
}
});
this.callParent(arguments);
}
或者,如果它们都属于某种 xtype,但跨多个容器,则派生出特殊的 xtype
,因此而不是
items:[{
xtype:'textfield',
labelWidth:125,
},{
xtype:'textfield',
labelWidth:125,
},{
xtype:'textfield',
labelWidth:125,
使用
items:[{
xtype:'mytextfield'
},{
xtype:'mytextfield'
},{
xtype:'mytextfield'
mytextfield 被定义为
Ext.define('MyTextField',{
extend:'Ext.form.field.Text',
xtype:'mytextfield',
labelWidth:125,
...
});
关于javascript - Extjs 6 : What's the best practice to handle repeated configuration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37884814/