Question

I am using a Cairngorm MVC architecture for my current project.

I have several commands which use the same type of function that returns a value. I would like to have this function in one place, and reuse it, rather than duplicate the code in each command. What is the best way to do this?

Was it helpful?

Solution

Create a static class or static method in one of your Cairngorm classes.

class MyStatic
{
    public static function myFunction(value:String):String
    {
        return "Returning " + value;
    }
}

Then where you want to use your function:

import MyStatic;

var str:String = MyStatic.myFunction("test");

Another option is to create a top level function (a la "trace"). Check out this post I wrote here.

OTHER TIPS

You have lots of options here -- publicly defined functions in your model or controller, such as:

var mySharedFunction:Function = function():void
{
   trace("foo");
}

... static methods on new or existing classes, etc. Best practice probably depends on what the function needs to do, though. Can you elaborate?

Create an abstract base class for your commands and add your function in the protected scope. If you need to reuse it anywhere else, refactor it into a public static method on a utility class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top