我正在尝试为我的 Ext 对象创建自定义属性值(基于函数的条件),而不是仅指定一个值。
示例 1:
旧代码(工作)
this.buttons = [
{
text: 'Save',
新代码(不起作用)
this.buttons = [
{
text: function() {
return 'Save X';
},
示例 2:
旧代码(工作)
}, {
width: 270,
labelAlign: 'right',
xtype: 'textfield',
name: 'user_id',
fieldLabel: 'User ID',
hidden: true
}]
新代码(不起作用)
}, {
width: 270,
labelAlign: 'right',
xtype: 'textfield',
name: 'user_id',
fieldLabel: 'User ID',
hidden: function() { return true; }
}]
示例 3:
根据条件完全忽略整个文本字段对象(惰性实例):
}, {
width: 270,
labelAlign: 'right',
xtype: 'textfield',
name: 'employee_number',
fieldLabel: 'Employee Number'
}]
最佳答案
你根本不能这样做。无法用函数替换类型。在您的情况下,您将函数引用分配给预计为 bool 值的变量,对于字符串也是如此。
解决方案A。
您应该考虑为自己编写一个现场工厂。在该工厂中,您可以在分配配置之前执行任何功能。 (与 B 类似,但可用于减少函数调用)
解决方案B。
使用函数引用本身。然后这个应该被执行。 (免除类扩展的要求并且超过可重用性)
// The data store containing the list of states
var states = Ext.create('Ext.data.Store', {
fields: ['abbr', 'name'],
data : [
{"abbr":"AL", "name":"Alabama"},
{"abbr":"AK", "name":"Alaska"},
{"abbr":"AZ", "name":"Arizona"}
//...
]
});
Ext.namespace('my.util.helper');
my.util.helper.decideHide = function() { return true; }
// Create the combo box, attached to the states data store
Ext.create('Ext.container.Container', {
renderTo: Ext.getBody(),
items: [{
xtype: 'combo',
fieldLabel: 'Choose State',
store: states,
queryMode: 'local',
displayField: 'name',
valueField: 'abbr',
test: my.util.helper.decideHide(),
listeners: {
afterrender: function(n) {
alert(n.test);
}
}
}]
});
解决方案C。
在这种情况下我最常使用的解决方案是简化 if else 语句
// ... // more code
{
text: myCondition ? 'Text A' : 'Text B',
// more code
}
// ... // more code
关于object - 分机JS 4 : Custom object property value based on condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12219991/