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.
- Ext.each(myArry, function(r){
- this.doSomething(r);
- });
Ext.each(myArry, function(r){
this.doSomething(r);
});
This next code maintains scope within the each loop.
- Ext.each(myArry, function(r){
- this.doSomething(r);
- }, 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
- myCmp.on('myevent', this.myHandler);
myCmp.on('myevent', this.myHandler);
This next code maintains scope within the event handler.
- 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
- listeners: {
- myevent: {
- fn: this.myHandler,
- scope: this
- }
- }
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.
- buttons: [{
- text: 'Do Something',
- handler: this.doSomething,
- scope: this
- }]
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.
- Ext.Msg.prompt(
- 'Do Something',
- 'Something',
- this.doSomething,
- this
- );
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.
|