How can I access class variables in ExtJS event handler?

this.getUrl = 'test';
this.items.add(
      new Ext.form.Checkbox(
            {
              listeners: {
                check: function(checkbox, checked) {
                  alert(this.getUrl);
                },
             }
       )
)

How do I access this.getUrlthe check handler?

+5
source share
3 answers

There are several ways to access a property getUrl. Here are a few options:

1. Use Ext.getCmp . If you have installed idextPsel (or other extjs component that you use) for your FormPanel, you can access it using the method Ext.getCmp(). In this way,

 var yourComponent = Ext.getCmp('yourComponentId');
 alert(yourComponent.getUrl);

2. OwnerCt. ( ), OwnerCt.

3. refOwner. ref, , .

, .

+4

, , Ext "scope":

this.getUrl = 'test';
this.items.add(
    new Ext.form.Checkbox(
            {
            listeners: {
                check: function(checkbox, checked) {
                    alert(this.getUrl);
                },
                scope: this
            }
    )
)
+11

( this). , , , - :

var getUrl = 'test';  // now it just a regular variable
this.items.add(
      new Ext.form.Checkbox(
            {
              listeners: {
                check: function(checkbox, checked) {
                  alert(getUrl); // still available - lexical scope!
                },
             }
       )
)

If you really want the parent to be accessible as thisin an event handler, you can use Ext.Function.bindto change the scope:

this.getUrl='test';
this.items.add(
      new Ext.form.Checkbox(
            {
              listeners: {
                check: Ext.Function.bind( function(checkbox, checked) {
                  alert(this.getUrl);
                }, this ),  // second arg tells bind what to use for 'this'
             }
       )
)

Update: Ext.Function.bindis an ExtJS 4 function. If you use ExtJS 3.x or lower, you can use Function.createDelegateat the same end:

this.getUrl='test';
this.items.add(
      new Ext.form.Checkbox(
            {
              listeners: {
                check: function(checkbox, checked) {
                  alert(this.getUrl);
                }.createDelegate(this)
             }
       )
)
+7
source

All Articles