ExtJS中combo組件設置默認值插件

相信很多人都遇到了在ExtJS框架中設置combo組件默認值的需求,ExtJS框架並沒有提供現成的配置項或者方法來解決此問題,本人認爲主要是因爲此種需求的應用場景有限且很難完成適應於不同場景的實現。

combo組件的設值其實很簡單:

var record = store.getAt(index);
combo.setValue(record.get(valueField));
即根據index獲取store裏面需要設置默認值的model對象,然後調用combo組件的setValue方法即可。但是選擇設值的“時機”,達到“默認值”的效果,可能就顯得比較複雜了。
設置默認值的需求場景一般是在Form查詢表單上,提供一個默認的查詢項目。多數情況下,這種需求的combobox組件一般位於諸如tabpanel這樣的模塊主面板下的form中,或者位於window組件下的form中。前者可以通過監聽form的afterrender事件實現;後者可以通過監聽window的show事件實現。

如果在項目中combo組件設置默認值的需求場景很少,可以視情況在combo組件的父容器裏直接添加相關監聽事件來設置默認值。如果應用場景比較多,通過插件的方式配置就比較明智了。

下面展示本人所開發的實現combo組件設置默認值功能的插件,代碼如下:

/**
 * 設置combo默認值插件
 * By Mask
 */
Ext.define('Ext.ux.combo.DefaultValuePlugin', {
    extend: 'Ext.AbstractPlugin',
    alias: ['plugin.defaultvalue', 'plugin.defaultvalueplugin'],
    parentType: 'form',
    displayIndex: 0,
    init: function(combo) {
        var me = this;
        me.combo = combo;
        combo.on('afterrender', me.setParentEvent, me, {single: true});
    },
    setParentEvent: function() {
        var me = this,
            parentType = me.parentType;
            parent = me.combo.up(parentType);
        if(parent) {
            if(parentType == "form") {
                parent.on('afterrender', me.setDefaultValue, me);
            } else if(parentType == "window") {
                parent.on('show', me.setDefaultValue, me);
            }
        }
    },
    setDefaultValue: function() {
        var me = this,
            combo = me.combo,
            store = combo.getStore(),
            valueCode = combo.valueField,
            record;
        if(combo.queryMode == "remote" && store.getCount() <= 0) {
            combo.lastQuery = combo.allQuery;
            store.load({
                params: combo.getParams(combo.allQuery),
                callback: function(records, operation, success) {
                    if(success == true) {
                        record = records[me.displayIndex];
                        if(record) {
                            combo.setValue(record.get(valueCode));
                        }
                    }
                }
            });
        } else {
            record = store.getAt(me.displayIndex);
            if(record) {
                combo.setValue(record.get(valueCode));
            }
        }
    },
    destroy: function() {
        delete this.combo;
    }
})
此插件包含兩個配置項:
1.parentType:可以設置爲’form’或’window’屬性,分別對應combo組件位於諸如tabpanel這樣的模塊主面板下的form中和位於window組件下的form中
2.displayIndex:顯示的默認值在store中的位置,默認爲0,即顯示第一項。
插件同時支持combo組件數據源查詢的local模式和remote模式。

使用方式很簡單,以plugin的方法配置進入combobox組件中即可:

{
    xtype: 'combo',
    fieldLabel: '遠程模式',
    queryModel: 'remote',
    store: remoteStore,
    displayField: 'username',
    valueField: 'forumid', 
    plugins: {
		ptype: 'defaultvalue',
		displayIndex: 2,
		parentXType: 'form'
    }
}

本文第一次發表於:[ExtJS]combobox設置默認值插件

更多ExtJS相關內容請點擊:戴面罩的怪傑



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章