extjs - 我们如何在 extjs 中为视图的不同元素调用相同的侦听器方法?
问题描述
我有一个视图,从中触发一个事件并在其控制器中监听。我们如何为视图中的多个元素调用同一个侦听器。
如果我将相同的 itemId 添加到两个按钮,则只有最后一个获得渲染器。所以,仅供参考,我在这里的示例代码中给出了相同的 id。
当我点击两个按钮时,我想调用“showPopup”,当然,不同的参数。
看法:
{
xtype : 'container',
layout : 'hbox',
items : [ {
xtype : 'datefield',
fieldLabel : 'Date 1',
},
{
xtype : 'button',
itemId: 'myPopup',
listeners : {
click : function() {
this.fireEvent('displayPopup', 'abc','def')
}
}
},
{
xtype : 'datefield',
fieldLabel : 'Date 2',
},
{
xtype : 'button',
itemId: 'myPopup',
listeners : {
click : function() {
this.fireEvent('displayPopup', 'xyz','lmn')
}
}
} ]
},
控制器:
listen : {
component : {
'myPopup'' : {
displayPopup : 'showPopup'
}
}
},
showPopup: function(param1, param2){
//my code
}
解决方案
您可能已经注意到 itemId 是唯一的(因此,只有最后一个正在呈现),因为您的控制器设置为侦听特定组件 itemId,在您的情况下,它只会在您的最后一个组件中触发,我的解决方案是不听特定的组件,而只是从您的按钮单击事件中调用控制器功能。
控制器:
Ext.define('MyController', {
extend: 'Ext.app.ViewController',
alias: 'controller.MyController',
displayPopup: function(param1, param2) {
console.log(`param1: ${param1}`);
console.log(`param2: ${param2}`);
}
});
看法:
{
xtype: 'container',
layout: 'hbox',
controller: 'MyController', //set the controller
renderTo: Ext.getBody(),
items: [{
xtype: 'datefield',
fieldLabel: 'Date 1',
}, {
xtype: 'button',
listeners: {
click: function() {
//get ref of controller and call its function
this.up('container').getController().displayPopup('abc', 'def')
}
}
}, {
xtype: 'datefield',
fieldLabel: 'Date 2',
}, {
xtype: 'button',
listeners: {
click: function() {
//get ref of controller and call its function
this.up('container').getController().displayPopup('xyz', 'lmn')
}
}
}]
}
像这样,您根本不需要任何 itemdId。
如果您仍想从控制器中收听特定组件,您可以使用组件查询
listen: {
component: {
'container[itemId=MyContainer] button': {
//listen to displayPopup from all buttons inside a container with itemId = MyContainer
displayPopup: function(param1, param2) {
console.log(`fired from controller listen, param1=${param1}, param2=${param2}`);
}
}
}
}