One of the problems with ASFunction is that it will not let you call class methods. This is inconvenient if you are using your own custom class that builds an interface, and you need to have clickable links within a text field. A couple of solutions that I have seen uses a homemade proxy class or the built-in Delegate class to do it, but there is another way to do it that uses the same technique that is used within the XML object and within event handlers to retain the handle to the class instance. When an ASFunction link is clicked, the text field automatically looks to the parent movie clip for the function to call. A proxy function is placed in the text field’s parent movie clip, then a “parent” variable is created to hold the reference to the class instance. That variable is visible within the proxy function, and allows the function to then “redirect” to the class method.
class ASFunctionTest
{
private var pBaseTimeline:MovieClip;
public function ASFunctionTest(baseTimeline:MovieClip)
{
pBaseTimeline = baseTimeline;
pBaseTimeline.createEmptyMovieClip("holderClip", pBaseTimeline.getNextHighestDepth());
pBaseTimeline.holderClip.createTextField("testField", 0, 0, 0, 200, 40);
pBaseTimeline.holderClip.testField.html = true;
pBaseTimeline.holderClip.testField.htmlText = '<a href="asfunction:handlerFunction,foo">The quick brown fox</a>';
var parent:ASFunctionTest = this;
// Assign a function to the movie clip holding the text field. This is what will be called
// By the asfunction call. This will act as a proxy for the class method.
pBaseTimeline.holderClip.handlerFunction = function(parameter:String)
{
// Use a variable "parent" with function scope to retain the handle
// to the class instance
parent.handlerMethod(parameter);
}
}
private function handlerMethod(parameter:String)
{
trace("ASFunction handler called with parameter: " + parameter);
}
}
Thanks a bunch Nathan! Simple and elegant solution. Kudos
Nathan
Thanks for the pointer – I was able to make this work in a simple example, but found problems when using cellRendering API that I got from http://philflash.inway.fr. synchronicity strikes again. (no problem with phil’s code, jut my use of it!!)
However I managed to get it going with one (yes only one) filthy hardcoded variable (grr I spent days trying to get into best practice, but the deadline got in the way of nice code)
cheers, and beers if ya ever get to Melbourne Australia!
jr
Glad to help. Yah, class scope can be a pain in the behind!
Pingback: Christopher Fannon » Fun with Flash: ‘asfunction’ calls within a Class instance.