使用relayEvents() 方法...好吧,从子字段传递change 事件。
下面是一些基本的代码:
Ext.define('My.Container', {
extend: 'Ext.Container'
,layout: 'form'
,initComponent: function() {
this.callParent(arguments);
// i want to support nested containers
this.parseContainerItems(this);
}
,onItemAdded: function(item) {
if (item instanceof Ext.Container) {
this.parseContainerItems(item);
} else if (item instanceof Ext.form.field.Base) {
this.relayEvents(item, ['change']);
}
}
,parseContainerItems: function(ct) {
if (ct.items) {
ct.items.each(this.onItemAdded, this);
}
}
});
示例用法:
Ext.create('My.Container', {
renderTo: 'ct' // render to a test div
,height: 200
,width: 200
,items: [{
xtype: 'textfield', name: 'foo', fieldLabel: 'Foo'
},{
xtype: 'container'
,items: [{
xtype: 'checkbox', name: 'bar', fieldLabel: 'Bar'
}]
}]
,listeners: {
change: function(item, newValue, oldValue) {
console.log(Ext.String.format('Value of item {0} changed from {1} to {2}', item.name, oldValue, newValue));
}
}
});
走得更远……
正如我所说,我的实现非常初级,因为它只支持通过配置添加到容器中的字段。如果您想让该组件灵活,您必须处理在组件创建后添加的字段。
为此,您需要观察容器的 add 事件,以便从创建后添加的字段进行中继。文档说这个事件是从子容器中冒出来的,但从我的测试来看,它没有:-(所以(在修复之前?)你还必须观看子容器的 add 事件。
这是parseContainerItems() 方法的更新代码:
parseContainerItems: function(ct) {
ct.on('add', function(me, item) {
this.onItemAdded(item);
}, this);
if (ct.items) {
ct.items.each(this.onItemAdded, this);
}
}
如果您还想支持动态删除字段的可能性,那么事情就会出错...您必须实现自己的 relayEvents() 版本,因为据我所知,这是不可能的停止使用分机提供的事件中继事件。然后您必须观看 remove 事件以删除您添加到子字段和容器的侦听器。