Search code examples
javascriptextjsextjs3

extjs button scope


I am trying to understand scope in the below scenario. When calling searchTerms, this under the scope:this refers to the searchTerms function rather than the panel itself. It seems to be different from what I observe from other examples. May I know what mistakes did i make?

function searchTerms(){
       var searchGrid = new Ext.grid.GridPanel({

        });

        var searchPanel = new Ext.form.FormPanel({
            region: 'south',
            height:150,
            items:[
            {
                xtype: 'textfield',
                fieldLabel: 'Keywords',
            },{
                xtype: 'textfield',
                fieldLabel: 'Label',
            },{
                xtype: 'datefield',
                fieldLabel: 'Valid till'
            },new Ext.Button({
                text: 'crawl',
                scope: this,
                handler: function(b,e){
                    Ext.Ajax.request({^M
                        url: '/discovery/tsearch',^M
                        params: {^M
                            keywords: this.items[0].getValue(),
                            label: this.items[1].getValue(),
                            valid: this.items[2].getValue(),
                        },
                    });
                }
            }),],
        });

        var regionPanel = new Ext.Panel({
            title: 'search',
            layout: 'border',
            items: [searchPanel, searchGrid]
        });

    return regionPanel;
}

Solution

  • I think you meant to do this:

    function searchTerms(){
       var searchGrid = new Ext.grid.GridPanel({
    
        });
    
        var searchPanel = new Ext.form.FormPanel({
            region: 'south',
            height:150,
            items:[
            {
                xtype: 'textfield',
                fieldLabel: 'Keywords',
            },{
                xtype: 'textfield',
                fieldLabel: 'Label',
            },{
                xtype: 'datefield',
                fieldLabel: 'Valid till'
            }],
        });
        searchPanel.add(new Ext.Button({
                text: 'crawl',
                scope: searchPanel,
                handler: function(b,e){
                    Ext.Ajax.request({
                        url: '/discovery/tsearch',
                        params: {
                            keywords: this.items[0].getValue(),
                            label: this.items[1].getValue(),
                            valid: this.items[2].getValue(),
                        },
                    });
                }
            })
        );
        var regionPanel = new Ext.Panel({
            title: 'search',
            layout: 'border',
            items: [searchPanel, searchGrid]
        });
    
    return regionPanel;
    }