views:

65

answers:

3

Is there arguments that work most of the time in AS3? I want a code setup that will works most of the time. Any suggestions?

Books break it down, but don't show how the programmers arrived at their conclusions. This could turn in to a discussion question, but if there's a secret I want to know.

WHAT I'M AFTER
- an argument structure - learn a process to perform function calls
- expand variables beyond my "20 lines of code"
- manage variables, events, and functions systematically

2 examples that do the same thing, but are structured different "go figure"

//Example #1 "move the ball"
addEventListener(Event.ENTER_FRAME, onLoop, false, 0, true);

function onLoop(evt:Event):void{
ball1.x += 5; 
 }


    //Example #1 "move the ball" 
    function moveBall(e:Event):void {
    ball2.x += 5;
    }
    ball2.addEventListener(Event.ENTER_FRAME,moveBall);

The if...else argument "ball loop"

//growing collection of arguments
addEventListener(Event.ENTER_FRAME,myEnterFrame);
    function myEnterFrame(event:Event) {
    if (ball.x>800) {
    ball.x=-160;
    } else {
    ball.x+=5;
    }
    }

DIFFERENT WAY OF DOING IT "from Adobe livedocs"

EQUIVILANT BOOLEANS
var flag:Boolean = true;
var flag:Boolean = new Boolean(true);
var flag:Boolean = Boolean(true);

EQUIVILANT STRINGS
var str:String = new String("foo");
var str:String = "foo";
var str:String = String("foo");

COMMENT
a functional style like lambda calculus would be a good example "more math less syntax and class structures"

EVENT LISTENERS
http://www.adobe.com/devnet/actionscript/articles/event_handling_as3.html

+1  A: 

Is there arguments that work most of the time in AS3? I want a code setup that will works most of the time.

I don't think I understand your question. Can you give an example?

EDIT

Ok, now that I better understand your questions, here are my 2 cents.


FIRST EXAMPLE

In your first example you are showing how both "this" and "ball2" are Objects which either implement IEventDispatcher or inherit from EventDispatcher. In the first case, which can be rewritten like this:

this.addEventListener(Event.ENTER_FRAME, onLoop, false, 0, true);

You are saying, whenever there is an Event.ENTER_FRAME event fired off by this, run the function onLoop. As pointed out in the other answer, the last three arguments are optional, but I always include them since the default for useWeakReference is false and I like to set it to true. The addEventListener function can only be run on Objects which have the addEventListener method (ie. Classes that extend EventDispatcher, or implement IEventDispatcher.)

Whether you choose to use the first method or the second is really dependent on use-case and preference. Let me give you an example.

package {
    class BallHolder extends MovieClip {
        private var _balls:Array;
        public function BallHolder():void {
            this.addEventListener(Event.ENTER_FRAME, _updateBalls, false, 0, true);
            _balls = [];
            var ball:Ball;
            for (var i:Number = 0; i < 10; i++) {
                ball = new Ball();
                _balls.push(ball);
                ball.x = i * ball.width;
                ball.y = 100;
                addChild(ball);
            }
        }

        private function _updateBalls($evt:Event):void {
            // lets move the balls randomly
            var _x:Number = 0;
            var _y:Number = 0;
            for (var i:Number = 0; i < _balls.length; i++) {
                _x = Math.round(Math.random() * 10) - 5;
                _y = Math.round(Math.random() * 10) - 5;
                _balls[i].x += _x;
                _balls[y].y += _y;
            }
        }

     }
}

package {
    class Ball extends MovieClip {
        public function Ball():void {
            this.graphics.beginFill(0x00ffff, 1);
            this.graphics.drawCircle(25, 25, 25);
            this.graphics.endFill();
        }
    }
}

In the above example, the BallHolder loops through 10 times, creating a new Ball instance, adding it to the DisplayList and pushing it onto an array called _balls. Right after it creates each ball, it places it at (the index * the ball width, 100), so if the balls are 50 pixels in diameter (like the example) then they are placed at (0, 100), (50, 100), (100, 100), etc.

In addition, the BallHolder also has an ENTER_FRAME event handler that loops through each of the balls and updates their positions randomly.

Compare that to this:

package {
    class BallHolder extends MovieClip {
        private var _balls:Array;
        public function BallHolder():void {
            _balls = [];
            var ball:Ball;
            for (var i:Number = 0; i < 10; i++) {
                ball = new Ball(i);
                _balls.push(ball);
                addChild(ball);
            }
        }
    }
}

package {
    class Ball extends MovieClip {
        public function Ball($index:Number):void {
            this.graphics.beginFill(0x00ffff, 1);
            this.graphics.drawCircle(25, 25, 25);
            this.graphics.endFill();
            this.addEventListener(Event.ENTER_FRAME, _updatePosition, false, 0, true);
            setPosition($index);
        }

        public function setPosition($index:Number):void {
            y = 100;
            x = $index * width;
        }

        private function _updatePosition($evt:Event):void {
            // lets move the ball randomly
            x += Math.round(Math.random() * 10) - 5;
            y += Math.round(Math.random() * 10) - 5;
            x += _x;
        }
    }
}

Now, all the BallHolder does is create instances of Ball and store them in an array. The Ball does all of the work as far as setting its position and updating it's position.


SECOND EXAMPLE

Still not sure what you mean here. It is quite common to have if/else if/else and switch constructs in event hanlder functions. Do you have a specific question about doing that?


THIRD EXAMPLE

Personally I always use

var flag:Boolean = true;
var str:String = "foo" 

and of course

var arr:Array = [];

For the first two, they are built-in classes (or data types) and don't have constructors. Saying something like var str:String = String("foo"); and var flag:Boolean = Boolean(true); are just ways of casting, which is unnecessary in this case, because you are casting them to the same type.

In addition, using [] for arrays is faster than new Array() because the Array constructor takes a single optional argument to create an array of given size. The [] construct does this for you without extra overhead.

sberry2A
Some people add the same listeners to their animations, but really don't know why etc.
VideoDnd
Seeing some "common practices" and reasons now, thanks.
VideoDnd
A: 

I would suggest you read up on event handlers on Adobe's site. http://www.adobe.com/livedocs/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&amp;file=00000139.html

From the site, here is the function definition of addEventListener:

function addEventListener(eventName:String, 
                        listener:Object,
                        useCapture:Boolean=false,
                        priority:Integer=0,
                        useWeakReference:Boolean=false):Boolean;

The last three arguments have default values (false, 0, false) so those can be left out when you call the function. The first two arguments are always required.

I think that the rest of your question would be best answered by learning about object oriented programming in AS3. Here is one guide: http://www.adobe.com/devnet/actionscript/articles/oop_as3.html

Nathan Villaescusa
I strongly advise you understand what you're giving up if you leave useWeakReference as false. Many developers set this to True, because otherwise it can cause issues with memory management. It's a tangential issue and probably not something you'd need to worry about with small scale projects, but Grant Skinner sets his to true if that carries any weight for you: http://www.gskinner.com/blog/archives/2006/07/as3_weakly_refe.html
Myk
You are correct. I left that there since those are the default values and I did not want to overly complicate the answer. If at any point in a program an event listener is no longer needed the programmer should call removeEventListener(eventName:String, listener:Object) or set useWeakReference true to begin with.
Nathan Villaescusa
+1  A: 

Actually, many developers prefer to set useWeakReference to true, which requires that you plug in all five arguments into event listeners. The reason is that that way the listener doesn't hold a reference to the target that would prevent garbage collection - it's a memory management technique. Most really good AS3 devs will tell you to always use all five arguments, just to get to that point.

Also, generally speaking it's better to use a literal when you can. "text" instead of new String("text"), true instead of new Boolean(true). Complex reasons, but there's your short answer.

The answers to a lot of these questions can be found here, which is a document that attempts to standardize AS3 coding conventions. It's worth reading over!

Myk
what i needed! useWeakReferences true takes out the trash http://onflash.org/ted/2008/09/useweakreferencesboolean-false.php
VideoDnd