ExtJS: Handle anchor tag clicks

Just a note on handling anchor clicks in text. If you have a blob of HTML in text on a view... for instance:

{
    xtype: 'panel',
    html: '<span class="z-information-icon" data-qtip="Expected file fomart is CSV">&nbsp&nbsp</span>' +
          '&nbsp;&nbsp;<a id="importUsersDownloadTemplate" class="c-anchor-anchor" href="#">Download template</a>'
}

You can following similar code to that found in http://derpturkey.com/extjs-component-event-from-dom-click/.

What you will do is attach a listener directly to the DOM element. Then you can add a custom component event.

{
    xtype: 'panel',
    itemId: 'importDownloadTemplateMessage',
    margin: '5 0 0 0',
    html: '<span class="z-information-icon" data-qtip="' + localize('ExpectedFileFormat') + '">&nbsp&nbsp</span>' +
          '&nbsp;&nbsp;<a class="c-anchor-anchor" href="#">' + localize('DownloadTemplate') + '</a>',
    listeners: {
        click: {
            element: 'el',
            preventDefault: true,
            fn: function (e, target) {
                var el = Ext.fly(target);
                if (el.dom.nodeName === "A") {
                    var cmp = Ext.ComponentQuery.query('#importDownloadTemplateMessage')[0];
                    cmp.fireEvent('click', cmp);
                }
            }
        }
    }
}

This code adds a DOM listener that is attached to the el property. It will filter out clicks that are not part of the anchor tag. When an achor click occurs it will retrieve the component (due to scoping issues this is necessary) and fire the component event.

You then can add a handler for this event on your controller:

init: function init() {  
    var me = this;
    me.callParentMethod(init, arguments);
    me.control({
        #importDownloadTemplateMessage': {
            click: me.onDownloadTemplateClick
        }
    });
}

Alternatively... you can structure your view to be use components and attach a click event to the label. Although this method loses some semantic meaning since label will create a label element instead of an anchor element.

{
    xtype: 'panel',
    layout: 'hbox',
    items: [
        {
            xtype: 'panel',
            margin: '5 0 0 0',
            html: '<span class="z-information-icon" data-qtip="' + localize('ExpectedFileFormat') + '">&nbsp&nbsp</span>'
        },
        {
            itemId: 'fileImportTemplateLink',
            xtype: 'label',
            margin: '5 0 0 5',
            cls: 'c-anchor-anchor',
            text: localize('DownloadTemplate'),
            listeners: {
                click: {
                    element: 'el',
                    preventDefault: true,
                    fn: function (e, target) {
                        var cmp = Ext.ComponentQuery.query('#fileImportTemplateLink')[0];
                        cmp.fireEvent('click', cmp);
                    }
                }
            }
        }
    ]
}
comments powered by Disqus