Search code examples
extjsextjs4extjs4.1extjs4.2extjs5

Up function not working in event handler on element


I have the following code below which works as I would expect:

var container = Ext.create('Ext.Container', {
                    html: 'Click Me!',
                    listeners: {
                        click: {
                            element: 'el',
                            fn: function() {
                                Ext.Msg.alert('Test', 'It was clicked!');
                             }
                         }
                     }
                 });

Ext.create('Ext.panel.Panel', {
    itemId: 'mainContainer',
    renderTo: Ext.getBody(),
    border: false,
    layout: {
        type: 'vbox',
        align: 'stretch'
    },
    items: [container]
});

In this example, I'm just alerting some nonsense message, but I would actually like to get the itemId of the parent container using the 'up()' method, however it does not work as I would expect. For example if i change the click handler to this:

click: {
    element: 'el',
    fn: function() {
        console.log(this.up('panel'));
    }
}

then 'null' is logged. How come I cant use the up() function here and is there a way to change this code so I can use it?


Solution

  • To expand on Surya's answer, this in the event handler is the Ext.dom.Element instance that the event is raised on, rather than the Ext.Container instance.

    An alternative would be to add the listener using the on method so you can force the scope of the handler to the container instance.

    container.on({
            click: {
                element: 'el',
                fn: function() {
                    console.log(this.up('panel'));
                },
                scope: container
            }
    
        });
    

    Have a look at this Fiddle which shows it in action:

    https://fiddle.sencha.com/#fiddle/1cka