Showing posts with label action script. Show all posts
Showing posts with label action script. Show all posts

Thursday, February 21, 2008

Anonymous "functions" in Flex

I will not start this post with an introduction to what an anonymous function is. I assume most of you already know it. So, i was very happy with the notion of Function being a type in action script. That means i can define a function type and create multiple copies of it, probably not that useful. But i can pass around functions to other functions, treat them as values and perform operations on functions, i can combine functions in a way we write mathematic functions on paper, probably not exactly like that, because actionscript does not support operator overloading. Forget operator loading, actionscript does not support function overloading, it also does not allow a constructor to be private. What is wierd is that, private constructors were supported untill actionscript 2, but discarded in actionscript 3.

So as an example, consider this

function action(condition:Fucntion, how:Function, preProcess:Function, postProcess:Function)
{
while(condition())
{
preProcess();
how();
postProcess();
}
}

It is not important how we implement this, the important point is the concept of abstracting the operations/functions and creating reusable functions, and avoid code duplication. There are many more advantages of treating functions as values, a similar concept in C++ is a function object or a functor, but those uses and advantages in a later blog.

So, actionscript provides a function type, and also supports anonymous functions which is great, BUT BUT, the anonymous functions are screwed up, their scopes are not at all consistent. When you refer to the variable "this" in a anonymous function, the result is not similar when you refer "this" in a function defined by name. so we cannot do this,

remoteObj.send(args,
function(event:ResultEvent):void
{
PopupManager.closePopup(this);
}
, fault_handler_function);

The above results in a runtime error. So we have to do this

remoteObj.send(args, result_handler, fault_handler_function);

private function result_handler(event:ResultEvent):void
{
PopupManager.removePopup(this);
}


Why this inconsistency, and why isnt this specified anywhere in the documentation. Is there a actionscript specification these people are working on? Is it avilable anywhere on the internet?

An update to this subject, the solution is posted here.

I did a quick search and i found the specification for actionscript 3. http://livedocs.adobe.com/specs/actionscript/3/wwhelp/wwhimpl/js/html/wwhelp.htm. Is this supposed to be the specification for a language, well, it doesnt at all look like it and it is a total waste. It looks like just an another tutorial.