【问题标题】:Add change event handler for custom Container of ExtJS为 ExtJS 的自定义容器添加更改事件处理程序
【发布时间】:2013-05-17 07:59:27
【问题描述】:

我通过扩展Ext.container.Container 创建了一个视图,并给它一个alias widget.myCustomView。因为我在不同的地方使用它。

textfielddataview等一样的Ext表单组件的视图现在我使用xtype将这个视图添加到其他视图中,如下所示:

{
    xtype: 'myCustomView',
    itemId: 'myCustomView'
}

现在,我想添加change 事件处理程序,这样如果任何组件的change 被触发,我就可以触发myCustom 视图的change 事件。简而言之,做这样的事情。

{
    xtype: 'myCustomView',
    itemId: 'myCustomView',
    listeners: {
        'change' : function(viewObj, eOpts) {
             //do something
         }
    }
}

怎么做?

【问题讨论】:

    标签: events extjs extjs4 custom-component


    【解决方案1】:

    使用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 事件以删除您添加到子字段和容器的侦听器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-23
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多