0

I am using ExtJS 4.1.1. I extended a class from Ext.TabPanel, and added a new method "removeAllTabs()". The belowing is my code:

MyTabPanel = Ext.extend(Ext.TabPanel, {
    extend: 'Ext.tab.Panel',
    removeAllTabs:function(){
        this.items.each(function(item){
            this.remove(item);
        });
    }
}); 
tabPanel = Ext.create('MyTabPanel', {
    activeTab: 0,
    autoDestroy: false,
    defaults :{
        autoScroll: true,
        bodyPadding: 10,
        closeAction: "hide",
    },
    items: []
});

I can add some tabs to it dynamiclly like this:

tabPanel.add(App.tab1); tabPanel.add(App.tab2);

Then I call this methmod to remove all tabs at somewhere:

tabPanel.removeAllTabs();

No error is reported, but nothing could be removed.

Then I modified the method as this:

MyTabPanel = Ext.extend(Ext.TabPanel, {
    extend: 'Ext.tab.Panel',
    removeAllTabs:function(panel){
        panel.items.each(function(item){
            panel.remove(item);
        });
    }
}); 

Then I call this methmod at somewhere:

tabPanel.removeAllTabs(tabPanel);

It can works well.

Why doesn't "this" work? How can I use "this" to achieve this purpose?

Thanks!

old bird
  • 67
  • 5

3 Answers3

0

In your each callback, this is not the same this as in removeAllTabs

Solution: Use a variable to store the outer this

removeAllTabs: function () {
    var self = this;
    this.items.each(function(item){
        self.remove(item);
    });
}
Ferdi265
  • 2,879
  • 1
  • 17
  • 15
0

"this" changes between the 2 functions. removeAllTabs has the right "this" but the function passed to "each" has a different "this" You have to store a reference to "this" in a variable like "me" so that the inner function has a reference to the correct "this"

The inner function's "this" refers to the anonymous function passed in.

MyTabPanel = Ext.extend(Ext.TabPanel, {
    extend: 'Ext.tab.Panel',
    removeAllTabs:function(){
        var me = this;
        me.items.each(function(item){
            me.remove(item);
        });
    }
});
tabPanel = Ext.create('MyTabPanel', {
    activeTab: 0,
    autoDestroy: false,
    defaults :{
        autoScroll: true,
        bodyPadding: 10,
        closeAction: "hide",
    },
    items: []
}); 
Ray Perea
  • 5,640
  • 1
  • 35
  • 38
0

As an alternative you could specify the scope for your each() function and not change the other code at all:

removeAllTabs:function(){
    this.items.each(function(item){
        this.remove(item);
    }, this);
}        ^----- this is the scope

References:

zerkms
  • 249,484
  • 69
  • 436
  • 539