Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access class variables in an ExtJS event handler?

Tags:

extjs

extjs4

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

How do I access this.getUrl in the check handler?

like image 960
Bdfy Avatar asked May 11 '11 16:05

Bdfy


2 Answers

I wonder why nobody has suggested the obvious, just do it the Ext way and use the 'scope' config property:

this.getUrl = 'test';
this.items.add(
    new Ext.form.Checkbox(
            {
            listeners: {
                check: function(checkbox, checked) {
                    alert(this.getUrl);
                },
                scope: this
            }
    )
)
like image 62
mistaecko Avatar answered Nov 15 '22 05:11

mistaecko


Event handlers are usually called from a different scope (this value). If all you want is a single value in the handler, lexical scoping is the easiest way to go:

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

Or if you really do want the parent object available as this in your event handler, you can use Ext.Function.bind to modify 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.bind is an ExtJS 4 feature. If you're on ExtJS 3.x or lower, you can use Function.createDelegate to the same end:

this.getUrl='test';
this.items.add(
      new Ext.form.Checkbox(
            {
              listeners: {
                check: function(checkbox, checked) {
                  alert(this.getUrl);
                }.createDelegate(this)
             }
       )
)
like image 29
wes Avatar answered Nov 15 '22 03:11

wes