gpt4 book ai didi

javascript - Extjs 6 : What's the best practice to handle repeated configuration

转载 作者:行者123 更新时间:2023-11-29 19:12:21 26 4
gpt4 key购买 nike

当我定义一个 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 重复了几次。我想用一些常量或变量来代替这些神奇的数字。在 EXTJS 中执行此操作的正确方法是什么?


更新:以下两种方法效果不佳。

  1. 使用默认值适用于 labelWidth 和 width,但不适用于 tdAttrs。

  2. 通过initComponent方法,组件停止显示。

    初始化组件:函数(){

        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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com