Search code examples
javascriptextjsextjs4

Why extjs button handler doesn't work


I have a window containing some button after clicking 'cancel' nothing happens. I'm really confused what could I'm getting wrong:

Ext.define('Myapp.view.User.NewForm', {
    extend: 'Ext.window.Window',
    width: 610,
    height: 380,
    y: 50,
    resizable: false,
    closable: true,
    draggable: false,
    title: 'new user',

    items: [{
        buttons: [{
                text: 'save',
                iconCls: 'form-save'
            },{
                text: 'cancel',
                iconCls: 'form-cancel',
                scope: this,
                handler: this.cancel     
            }]
    }],
    cancel: function() { alert('cancel'); }

})

Solution

  • Like Lolo says, this.cancel is undefined at the time when you define your Form class.

    The standard solution for this problem is to create items array inside initComponent:

    Ext.define('Myapp.view.User.NewForm', {
        ...
    
        initComponent: function() {
            this.items = [{
                buttons: [{
                    text: 'save',
                    iconCls: 'form-save'
                },{
                    text: 'cancel',
                    iconCls: 'form-cancel',
                    scope: this,
                    handler: this.cancel     
                }]
            }];
    
            this.callParent();
        },
    
        cancel: function() { alert('cancel'); }
    
    });
    

    When initComponent is invoked this points to the instance of your Form as one would expect. In you code this pointed to the global window object which didn't contain the cancel function.