ExtJS中如何从视图向Store传递参数?(下拉框场景)
问题:ComboBox变更时如何动态更新Store的filter参数?
先看一下你提供的原始代码:
Store 代码
Ext.define('mycomponents.store.mystore', { extend: 'Ext.data.Store', alias: 'store.levels', model: 'mycomponents.model.mymodel', storeId: 'levels', restful: true, autoLoad: true, proxy: { type: 'ajax', headers: { 'Accept': '*/*', 'Cache-Control': 'no-cache', 'Content-Type': 'application/json', 'Authorization': localStorage.token }, extraParams: { sort: 'levelid', 'filter[active]': true, 'filter[idparent]': 0 }, reader: { type: 'json', root: 'data', successProperty: 'success' }, writer: { type: 'json', writeAllFields: true, encode: true, root: 'data' }, listeners: { exception: function (proxy, response, operation) { var error = Ext.decode(response.responseText); Ext.MessageBox.show( { title: 'REMOTE EXCEPTION', msg: error.message, icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK } ); } }, actionMethods: { read: 'GET' }, api: { read: 'http://url...', create: 'http://url...', update: 'http://url...', destroy: 'http://url...' }, autoSave: true }, constructor: function (config) { this.callParent([config]); } });
View 代码
var store = Ext.create('mycomponents.store.mystore', {}); Ext.define('mycomponents.view.myview', { extend: 'Ext.container.Container', id: 'leves', alias: 'widget.levels', xtype: 'levels', items: [ { xtype: 'combobox', ... } ] ... }
解决方案
你只需要给ComboBox添加change事件监听,在用户选择不同选项时,动态更新Store的extraParams里的filter[idparent]值,然后重新加载Store即可。具体实现如下:
修改后的View代码(重点看ComboBox部分)
var store = Ext.create('mycomponents.store.mystore', {}); Ext.define('mycomponents.view.myview', { extend: 'Ext.container.Container', id: 'leves', alias: 'widget.levels', xtype: 'levels', items: [ { xtype: 'combobox', // 假设你的ComboBox的valueField是对应idparent的字段,比如'value' valueField: 'value', displayField: 'text', // 其他原有配置... listeners: { change: function(combo, newValue, oldValue) { // 确保newValue有效时才更新参数 if (newValue !== null && newValue !== undefined) { // 更新Store的extraParams store.getProxy().setExtraParam('filter[idparent]', newValue); // 重新加载Store store.load(); } } } } ], // 可选:如果需要初始化时就用ComboBox默认值加载数据 initComponent: function() { this.callParent(arguments); var combo = this.down('combobox'); var initialValue = combo.getValue(); if (initialValue) { store.getProxy().setExtraParam('filter[idparent]', initialValue); store.load(); } } ... });
额外说明
- 如果你的Store不是在View里直接创建的,而是通过
storeId全局引用的,可以用Ext.getStore('levels')获取实例,替换上面的store变量:
var targetStore = Ext.getStore('levels'); targetStore.getProxy().setExtraParam('filter[idparent]', newValue); targetStore.load();
setExtraParam只会更新指定的参数,不会覆盖extraParams里的其他原有配置(比如sort、filter[active]),可以放心使用。- 如果需要清空
filter[idparent]参数,可以传入null或者调用clearExtraParams()方法后重新设置需要保留的参数。
这样就能实现下拉框变更时,动态给Store传递不同的filter[idparent]参数啦!
内容的提问来源于stack exchange,提问作者assembler
相关产品推荐
相关产品推荐

