Josh Brittain
Josh Brittain

Reputation: 2212

AS3 - Defining functions inside of other functions

When adding event listeners and defining their corresponding functions I find myself defining the function in the code of a constructor a lot. Something like this:

package
    {
        public class stuff extends Sprite
        {
            public function stuff()
            {
                minimizeBtn.addEventListener(MouseEvent.CLICK, minimizeOnClick);
                function minimizeOnClick(e:MouseEvent):void
                {
                       //do minimization stuff here
                }
            }
        }
    }

However, there is clearly another option to define it like any other method of the class. Something like this:

 package
    {
        public class stuff extends Sprite
        {
            public function stuff()
            {
                minimizeBtn.addEventListener(MouseEvent.CLICK, minimizeOnClick);
            }

            internal function minimizeOnClick(e:MouseEvent):void
            {
                //do minimization stuff here
            }
        }
    }

The second option may not really make sense because the function isn't really a method of the class. But my concern is that the first method will use up extra memory for each instance of the class. Which is the most efficient and correct way to do this and also does the first method take up extra memory or CPU time for each instance of the class?

Thanks!

Upvotes: 0

Views: 2234

Answers (1)

Marty
Marty

Reputation: 39466

The latter example is the correct way, and it's true that you should try encapsulate your addEventListener() and listening function within the relevant class. In your case, you may want to consider making a class for your minimizeBtn:

public class MinimizeButton extends SimpleButton
{

    public function MinimizeButton()
    {
        addEventListener(MouseEvent.CLICK, _onClick);
    }

    private function _onClick(e:MouseEvent):void
    {
        // do minimization stuff here
    }

}

MinimizeButton's _onClick() should then target the relevant instance of your class stuff and run whatever stuff needs to do from there.

This example's process is more like:

MinimizeButton: "I've been clicked, I should inform stuff so it can do something relevant."

Rather than:

stuff: "I'm going to sit and wait for MinimizeButton to get clicked, then I'll do what's required."

Upvotes: 1

Related Questions