Four Tips for Staying on Track With Scope in ExtJS
We have all been there, mucking around with code, thinking to ourselves "why does this component not have an X method?" or "where did all my scoped vars run off to?" spending valuable time debugging your code just to eventually find out that you have gone out of scope and didn't know it. The unfortunate thing is that its so incredibly easy to loose track of your scope, and not often are the results of whats going wrong making it glaringly obvious that your scope has been lost.
A solution that works for me has taken the shape of a sticky note - I affectionately refer to this as the "SCOPE DONKEY!" note. Its my reminder for things to look for when I get that icky feeling that there is a scope related problem. So here is the rundown:
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.
This next code maintains scope within the each loop.
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
This next code maintains scope within the event handler.
Just like with the each loop, we are passing in a scope as the third argument
NOTE: (thanks Rich Waters) this also applies to subscribing to events via the listeners config, for example:
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.
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.
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.




Don’t forget the listeners config version of adding events
Thanks for sharing your Scope Donkey! Luckily, the ExtJS docs also do a pretty good job of documenting all the places where you can pass scope into their api.
This is genius
Useful. I hope lots of people read this!
Don’t forget to add *callback* specifications.
Whenever you specify a function as a callback (eg, Store’s “load” callback), you might need to also specify scope, if the function expects to be a “member” of anything.
Thanks for sharing! I always struggled with this, now I understand.