问题描述
我想渲染一个具有初始值的 ComboBox。 ComboBox 由从某个 HTTP 端点加载数据的 JsonStore 支持。我希望显示显示字段,但我看到的是值。
作为一种解决方法,我可以等到商店加载完毕后再设置初始值。但对于这样一个简单的用例来说,这似乎是一种笨拙的解决方法。
是否有更简单的方法来为我的 ComboBox 呈现初始显示字段?
这是一个例子。您可以将此代码放在任何 ExtJS 3.4 Fiddle 中。
var remoteStore = new Ext.data.JsonStore({
url: 'https://jsonplaceholder.typicode.com/todos',autoLoad: true,fields: ['id','title']
});
var remoteCombo = new Ext.form.ComboBox({
fieldLabel: 'Remote Store (busted)',triggerAction: 'all',mode: 'local',store: remoteStore,valueField: 'id',displayField: 'title',value: '2',});
// Workaround: only set the value AFTER the store is loaded.
// remoteStore.on('load',() => remoteCombo.setValue('2'));
new Ext.FormPanel({
renderTo: Ext.getBody(),items: remoteCombo
});
解决方法
为什么不覆盖缺少的功能(是的,看起来缺少):
Ext.define('Override.form.ComboBox',{
override : 'Ext.form.ComboBox',defaultValue: null,initComponent : function() {
this.setDefaultValue();
Ext.form.Checkbox.superclass.initComponent.call(this);
},setDefaultValue: function() {
if(this.defaultValue !== null) {
if(this.getStore().lastOptions === null) {
this.getStore().on('load',function(store) {
this.setValue(this.defaultValue);
},this,{single: true});
} else {
// How to avoid else here? :-/
this.setValue(this.defaultValue);
}
}
}
});
//-------------------------
var remoteStore = new Ext.data.JsonStore({
url: 'https://jsonplaceholder.typicode.com/todos',autoLoad: true,fields: ['id','title']
});
var remoteCombo = new Ext.form.ComboBox({
fieldLabel: 'Remote Store (busted)',triggerAction: 'all',mode: 'local',store: remoteStore,valueField: 'id',displayField: 'title',defaultValue: '2',// <-- New Property
});
// Workaround: only set the value AFTER the store is loaded.
// remoteStore.on('load',() => remoteCombo.setValue('2'));
new Ext.FormPanel({
renderTo: Ext.getBody(),items: remoteCombo
});
我已经有大约 10 年或更长时间没有使用 ExtJs v3.4..