Well I’ll be damned, in my last post I wrote about how I was trying to figure out which class was calling addEventListener on a FlexSprite. I couldn’t figure out a way to get the name of the calling class, or the name of the method that called addEventListener(). Well, Almog Kurtser commented that there’s a trick you can do by using the Error class and the getStackTraceMethod() to parse out these strings.
If you call:
trace(new Error().getStackTrace()) you’ll get something that looks like:
Within that long string you have all sorts of information about every calling function all the way up the stack. You can parse that all out and figure out where in the application you were. You can do this from anywhere in your app.
So I updated the monkey patched event dispatcher example in my last post to use this method and lo and behold we can get the class name of the class that called addEventListener(). We even get the method name and the line number where addEventListener was called.
Now in the FlexSpy example you get much more information and can trace back exactly where the event listener was added. Sweet! A big thanks goes to Almog (and to Alex Harui who Almog references as his source of this little gem).
IMPORTANT NOTE: The Error.getStackTrace() method only works with the DEBUG version of your swf. If you export a release build then a call to Error.getStackTrace() won’t work.
- A while back Ben Clinkinbeard asked a question on flexcoders saying "Am I the only one who wishes EventDispatcher exposed its listeners?" The fundamental issue was that he wanted to get a list of all the event listeners that had been added to a given component. The approach: using FlexSprite…
- Pretty sweet logo, whoever designed that must be pretty much the best person in the world. Get your 360|Flex stuff here. And if you haven't registered for 360Flex, do that here.