2011-05-18 108 views
1

我們不能使用Ext.data.Store進行同步呼叫嗎?Ext Js Combobox - 同步呼叫設置值

我有一個模型,我正在店內加載。後來我將它綁定到一個組合框。這個流程正常工作。

但是,當我想要爲默認選擇設置組合的值時,我得到JS錯誤,說存儲區內沒有元素。原因是,在執行完所有JS之後,ajax調用來填充商店。我嘗試將異步屬性設置爲false,但仍然沒有運氣!

這裏是我的代碼片段:

var store = new Ext.data.Store({   
    proxy: { 
     type: 'ajax', 
     url: '/GetAccounts', 
     reader: { 
      type: 'json' 
     } 
    }, 
    async: false, //Tried this...no luck 
    cache: false, 
    autoLoad: true 
}); 

var simpleCombo = Ext.create('Ext.form.field.ComboBox', { 
    fieldLabel: 'For ', 
    renderTo: 'simpleCombo', 
    displayField: AccountName, 
    valueField: 'AccountId', 
    store: store, 
    queryMode: 'local', 
    forceSelection: true 
}); 

simpleCombo.setValue(store.getAt(0).get('AccountId')); //JS ERROR AT THIS LINE. No elements in the store 

回答

2

禁用組合商店填充到。不要混淆同步請求,你會凍結整個頁面(甚至瀏覽器),直到請求完成。

1

我張貼類似的東西在https://stackoverflow.com/a/12918140/1449525,但我把這種方法:

添加監聽到你的組合框以便當組合框實際呈現,所以應儘量將其值設置

listeners:{ 
    scope: this, 
    afterRender: this.selectFirstComboItem 
} 

然後將該方法添加到您的this(或您喜歡的任何地方)。

selectFirstComboItem: function(combo) { 
    // This will tell us if the combo box has loaded at least once 
    if (typeof combo.getStore().lastOptions !== "undefined") { 
     // Grab the first value from the store 
     combo.setValue(combo.getStore().first().get(combo.valueField)); 
    } 
    else { 
     // When the store loads 
     combo.getStore().on("load", function(store, items){ 
      // Grab the first item of the newly loaded data 
      combo.setValue(items[0].get(combo.valueField)); 
     }); 
    } 
}