Firing custom event from custom component and handle event in viewController

country_dev picture country_dev · Jan 26, 2016 · Viewed 8.2k times · Source

I have created a custom component that extends from Ext.Panel. I have added a click listener to the custom component so that when it's clicked it will fire an event. I am instantiating the custom component in a view and I want to handle the event thats fired from the custom component in the viewController associated with that view.

However, when I fire the event, it's not bubbling up to the viewController. Is there a way to fire an event on the global scope? How do I go about handling an event in a viewController where the component that fires the event is instantiated in the view associated with the view controller?

My custom component looks somthing like so:

Ext.define('MyApp.ux.CustomComponent', {
  extend: 'Ext.Panel',

  xtype: 'custom-component'

  initComponent: function() {
    var me = this;
    me.callParent();

    me.addListener({
      'render': function(panel) {
        panel.body.on('click', function() {
          me.fireEvent('customEventName');
        });
      }
    });

  }
});

I am instantiating my custom component in a view like so:

Ext.define('MyApp.view.main.Main', {
  extend: 'Ext.container.Container',

  controller: 'main'

  items: [{
    xtype: 'custom-component'
  }]
});

And in my viewController (for the view that im instantiating my custom component in) I have the following listener:

customEventName: function () {
  console.log('I have been fired');
}

Answer

abeyaz picture abeyaz · Jan 27, 2016

View controllers listen for child item listeners, but not manually fired events. So, you need to use listener config for this like this e.g.

Ext.define('MyApp.view.main.Main', {
    extend: 'Ext.container.Container',

    controller: 'main'

    items: [{
        xtype: 'custom-component',
        listeners: {
            customEventName: 'customHandlerNameInController'
        }
    }]
});

Now when you fire your custom event, your view controller method must work.