Articles: 843 | Categories: 148   
   
   
Home Articles Contact Us
 
 
 
 
Four Tips for Staying on Track With Scope in ExtJS (0 Comments)
Admin: Posted Date: April 4, 2010

 Using Ext.each or the each method of an array or store, etc. is the first easy way to loose scope. The following bit of code looses scope, so our doSomething method is not available inside of the each.

Four Tips for Staying on Track With Scope in ExtJS

Each

Using Ext.each or the each method of an array or store, etc. is the first easy way to loose scope. The following bit of code looses scope, so our doSomething method is not available inside of the each.

  1. Ext.each(myArry, function(r){  
  2.     this.doSomething(r);  
  3. });  
Ext.each(myArry, function(r){ this.doSomething(r); });

This next code maintains scope within the each loop.

  1. Ext.each(myArry, function(r){  
  2.     this.doSomething(r);  
  3. }, this);  
Ext.each(myArry, function(r){ this.doSomething(r); }, this);

The difference is in the third argument that passes scope to the each loop.

                      

Events

Setting up event handlers is another easy place to loose scope, and when the event finally fires off it quickly becomes unclear where the problem originated

  1. myCmp.on('myevent'this.myHandler);  
myCmp.on('myevent', this.myHandler);

This next code maintains scope within the event handler.

  1. myCmp.on('myevent'this.myHandler, this);  
myCmp.on('myevent', this.myHandler, this);

Just like with the each loop, we are passing in a scope as the third argument

  1. listeners: {   
  2.     myevent: {   
  3.         fn: this.myHandler,  
  4.         scope: this  
  5.     }  
  6. }  
listeners: { myevent: { fn: this.myHandler, scope: this } }

Buttons

A Buttons handler is scoped to the button component itself by default, so everything inside that handler has a this that references the button. Its not very often that I actually use a buttons handler to manipulate the button itself, so I need my scope somewhere else. Luckily the button config has a scope option.

  1. buttons: [{  
  2.     text: 'Do Something',  
  3.     handler: this.doSomething,  
  4.     scope: this  
  5. }]  
buttons: [{ text: 'Do Something', handler: this.doSomething, scope: this }]

Message Boxes

The MessageBox's callback is a similar situation to the Button, so we need to pass it a scope as well, this way we have access to this inside the handler.

         

  1. Ext.Msg.prompt(  
  2.     'Do Something',   
  3.     'Something',   
  4.     this.doSomething,   
  5.     this  
  6. );  
Ext.Msg.prompt( 'Do Something', 'Something', this.doSomething, this );

I hope these tips help you out - By paying special attention to these four areas you should be able to minimize those late night scope related debugging sessions.

 

 
 
Add a Comment:
 
(You must be signed in to comment on an article. Not a member? Click here to register)
   
Title:

Comments: