简体   繁体   中英

EXTJS add fireEvent to dynamically created elements using tpl

I have an array of objects that I apply to html using new Ext.XTemplate and then I use the result as my html to a panel. When I click the button everything is fine using delegate.

Question:

How can I add events to the dynamically added buttons, so that I can use them in a controller?

initComponent: function() {
    var me = this;

    var data = [{
        caption: 'Dashboard',
        myclass: 'dashboard'
    }, {
        caption: 'clients',
        myclass: 'clients'
    }];


    var myTpl = new Ext.XTemplate(
        '<table><tr>',
        '<tpl for="."><td>',
        '<div style="width:200px;background-color:#004544;" class="thumb-wrap">',
        '<button style="color:#fff;cursor:pointer;" class="{myclass}">{caption}</button>',
        '</div></td>',
        '</tpl></tr></table>');


    var htmlApplied = myTpl.apply(data);


    this.items = [{
        xtype: 'panel',
        html: htmlApplied,
        scope: me,
        listeners: {
            el: {
                delegate: 'button',
                click: function(clickcmp, button) {
                    console.log(clickcmp);
                    console.log(button);

                    switch (button.className) {
                        case 'dashboard':
                            this.fireEvent('menuload');


                            break;
                        case 'clients':
                            //alert('clients');
                            break;

                    }

                }
            }
        }
    }]

    this.addEvents({
        menuload: true
    });
}

Controller

Ext.define("Something.Control", {

     extend: 'Ext.app.Controller',

     refs: [],

     init: function() {
         this.control({
             'selector': {
                 menuload: this.activateMenu
             }
         });
     },

     activateMenu: function() {

     }

 });

Assuming selector matches the component code that you added above, what you're missing is the scope on the listener. By default, the scope will default to the inner panel. The scope: me needs to go down inside the el block:

el: {
    scope: this,
    delegate: 'div'
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM