ExtJS: component event from DOM click

I needed to define a custom event in a view that was rending its contents with a template. The view was a simple panel that used templates to render a fairly complicated display. Part of this display was supposed to trigger actions.

To do this required three steps:
1) Define the component event
2) Monitor for DOM click events
3) Trigger the component event on the DOM click event

 Ext.define('MyApp.view.FormStats', {
        extend: 'Ext.panel.Panel',
        alias: 'widget.formstats',

    /**
     * Step 1: Define the event
     */
    constructor: function (config) {
        var me = this;
        me.addEvents('thingClick')
        this.callParent(arguments);
    },

    /** 
     * Step 2: Monitor for DOM clicks
     */ 
    initComponent: function () {
        var me = this;
        this.on({
            afterrender: function () {
                this.mon(me.el, 'click', me.onDomClick, me);
            }
        });
        this.callParent(arguments);
    },

    /**
     * Step 3: Fire component event on DOM clicks
     */
    onDomClick: function (e, target) {
        var me = this,
            el = Ext.fly(target);
        if (el.hasCls('c-hyperlink-displayfield')) {
            me.fireEvent('thingClick', me, 'unprocessed');
        }
    },
}

Step 3 will be fired for all DOM click events in your view. The code filters these click events to elements that you are interested in. In the above example, if an element has the class c-hyperlink-displayfield we will fire the component event.

Finally, in your controller, you simply add an event handler for your new event as your would for any other component event.

    init: function init() {
        this.control({
            'formstats': {
                thingClick: function (sender, type) {
                    console.log('It worked!');
                }
            }
        });
    },
comments powered by Disqus