Flash AS 3 - Can you help me tidy up my repetitive code?

Hi there,

I am new to programming (specifically in Actionscript 3) and wondered if someone can show me a more efficient way / tidier way to code my six movie clip buttons....My attempt seems very repetitive and clumsy but I dont know how else to do it.

Hopefully the code is self explanatory but essentially what I have is 6 buttons that each perform almost identical operations when moused over / out.

Is it possible to streamline my code or is this ok given what I am trying to do?

Many thanks for your thoughts in advance.
Darryl [keybord]
// BUTTON COMMUNICATION
 
//---KEY 1 [start]
 
key1_button.buttonMode = true;
key1_button.addEventListener(MouseEvent.MOUSE_OVER, key1Over);
key1_button.addEventListener(MouseEvent.MOUSE_OUT, key1Out);
 
 
 
function key1Over(event:MouseEvent):void
{
        key1_button.gotoAndPlay('over');
}
function key1Out(event:MouseEvent):void
{
        key1_button.gotoAndPlay('out');
}
 
//---KEY 1 [finish]
 
//---KEY 2 [start]
 
key2_button.buttonMode = true;
key2_button.addEventListener(MouseEvent.MOUSE_OVER, key2Over);
key2_button.addEventListener(MouseEvent.MOUSE_OUT, key2Out);
 
 
 
function key2Over(event:MouseEvent):void
{
        key2_button.gotoAndPlay('over');
}
function key2Out(event:MouseEvent):void
{
        key2_button.gotoAndPlay('out');
}
 
//---KEY 2 [finish]
 
 
//---KEY 3 [start]
 
key3_button.buttonMode = true;
key3_button.addEventListener(MouseEvent.MOUSE_OVER, key3Over);
key3_button.addEventListener(MouseEvent.MOUSE_OUT, key3Out);
 
 
 
function key3Over(event:MouseEvent):void
{
        key3_button.gotoAndPlay('over');
}
function key3Out(event:MouseEvent):void
{
        key3_button.gotoAndPlay('out');
}
 
//---KEY 3 [finish]
 
 
//---KEY 4 [start]
 
key4_button.buttonMode = true;
key4_button.addEventListener(MouseEvent.MOUSE_OVER, key4Over);
key4_button.addEventListener(MouseEvent.MOUSE_OUT, key4Out);
 
 
 
function key4Over(event:MouseEvent):void
{
        key4_button.gotoAndPlay('over');
}
function key4Out(event:MouseEvent):void
{
        key4_button.gotoAndPlay('out');
}
 
//---KEY 4 [finish]
 
 
//---KEY 5 [start]
 
key5_button.buttonMode = true;
key5_button.addEventListener(MouseEvent.MOUSE_OVER, key5Over);
key5_button.addEventListener(MouseEvent.MOUSE_OUT, key5Out);
 
 
 
function key5Over(event:MouseEvent):void
{
        key5_button.gotoAndPlay('over');
}
function key5Out(event:MouseEvent):void
{
        key5_button.gotoAndPlay('out');
}
 
//---KEY 5 [finish]
 
 
//---KEY 6 [start]
 
key6_button.buttonMode = true;
key6_button.addEventListener(MouseEvent.MOUSE_OVER, key6Over);
key6_button.addEventListener(MouseEvent.MOUSE_OUT, key6Out);
 
 
 
function key6Over(event:MouseEvent):void
{
        key6_button.gotoAndPlay('over');
}
function key6Out(event:MouseEvent):void
{
        key6_button.gotoAndPlay('out');
}
 
//---KEY6 [finish]

Open in new window

LVL 1
keybordAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

julianopolitoCommented:
Like this?
var btns:Array = [key1_button,key2_button,key3_button,key4_button,key5_button,key6_button];
for(var i:int = 0; i < btns.length;i++){
	bnts[i].buttonMode = true;
	btns[i].addEventListener(MouseEvent.MOUSE_OVER, keyOver);
	btns[i].addEventListener(MouseEvent.MOUSE_OUT, keyOut);
}
function keyOver(e:MouseEvent):void{
        e.currentTarget.gotoAndPlay('over');
}
function keyOut(e:MouseEvent):void{
        e.currentTarget.gotoAndPlay('out');
}

Open in new window

0
julianopolitoCommented:
Other option is to create a component class for the key buttons with encapsulated functionality (wich would be the best approach). Take a look at the class below (copy that into a .as file in the same fla folder) and then in flash cs3 put the name of the class in the properties of the movieclip
package{
	//KeyButton.as
	import flash.display.*;
	import flash.events.*;
 
	public class KeyButton extends MovieClip{
		public function KeyButton(){
			addEventListener(MouseEvent.MOUSE_OVER,keyOver);
			addEventListener(MouseEvent.MOUSE_OUT,keyOut);
		}
		private function keyOver(e:MouseEvent):void{
        	e.currentTarget.gotoAndPlay('over');
		}
		private function keyOut(e:MouseEvent):void{
        	e.currentTarget.gotoAndPlay('out');
		}
	}
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
keybordAuthor Commented:
dude, thats excellent!  I was sure there was a better way to do it... ;o)

May take me a bit to understand exactly how classes work (and how the 'currentTarget' knows to play the 'key' movieclip and not look for the 'over' or 'out' frames on the main timeline where the script is???) but this is a fine solution.

Thanks for your time,
Darryl
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

julianopolitoCommented:
It's simple. Take a look in the documentation for events in as3 . Every event creates a Event object and dispatches it with the event message. Look to the function :
private function keyOver(e:MouseEvent):void{
        e.currentTarget.gotoAndPlay('over');
}
keyOver was registered as a listener function to the mouse_over event. Whenever there is an mouse over the button, as3 will dispatch that event along with an event (MouseEvent object) with some additional information about that event. For example, this "e" object in the parameter , which is an mouseevent obj has more info on that event in its properties. If trace(e.localX) you can get the x position of the mouse relative to the button object by the time of the mouse over. The properties target and currentTarget are the ones common to every event , they are references to the ones generating or dispatching the event, and they are part of the Event class, which in turn is the super class for all event classes. Target is the object being clicked, currentTarget is an object that is clicked too, but it may be in outer levels than the target.
Let me explain it in a easy way. Imagine that scenario, where you have a textfield, inside a button, that is inside a movieclip.
MovieClip
       |--Button
                |-- TextField
If you click the textfield, the button and movieclip also gets clicked one after another in a hierarchy order. And in flash the event model has a flow. This flow has two direction, and 3 distinct phases: Capture Phase, Target Phase, Bubbling Phase.
Capture phase - the click dispatches event for the movieclip, then button.
Target Phase - the inner object under the mouse is the target, so the target phase is when textfield dispatches the event
Bubbling Phase- the event bubbles up and again dispatches event for button , then movieclip (notice that the order is inverse now)

When you add an event listener to your button the default behavior is to listen for the bubbling phase. In that case of yours I think target would work the same as currentTarget because the key_button must be a simple button, so target == currentTarget. But As I did not know if it was a custom button with labels inside, currentTarget was the best choice because the listener was registered to the whole button.

I think this can be a good startint point for you to study. Read the dev guide for actionscript or buy a book on the subject. ;)

 
0
julianopolitoCommented:
Just to complete the info above I wrote so many info I forget the basic:
Back to the scenario
MovieClip
       |--Button
                |-- TextField
if you add event listener to button, and it is clicked/moused over, the event object will have target == the textfield and currentTarget == the button instance, because even though you are clicking the button, the textfield is inside and enabled to respond to events, so it is the real target, and the currentTarget is the guy currently being hit by the event flow.
0
keybordAuthor Commented:
Again, thank you for all this Juliano!  A good starting point indeed though I am sure I will have many more questions as I learn...


One interesting thing I noted that you may be able to comment on is that the first piece of shorter code actually increased the .swf file size by 1k.  This is obviously not an issue but if anything I was expecting the file size to drop by 1k or so as a result of streamlining my original code....odd no?
0
keybordAuthor Commented:
Sorry to bother you again Juliano but I am having some problems understanding how to actually use the class in my movie.

I understand how it should work but cant seem to find the right information on how to import it / call it in my actual .fla?

Most examples point to using code something along these lines:

import flash.KeyButton;
var Keybutton = Keybutton(key1_button);

I dont really see the realtionship with the 'var' or how to associate the class with my key movieclips?

If you would prefer that I post this as a new question (ie. new points) I will gladly do so.

Thank you
0
julianopolitoCommented:
Here is the answer.

-Put the .as file in the same folder as the .fla.
-Open the fla, open the library .
-Right Click the KeyButton movieclip in the library.
-Select Linkage...
-Check Export for Actionscript
-In the Class field, write KeyButton (it is case sensitive)
-Press OK button

Now you have associated the class file with the movieclip symbol. That means your movieclip is now registered as a KeyButton.

Now you do not have to import anything. Just use your movieclip as usual. If you want to create a new KeyButton from actionscript, there is no need to import anything, since its package is empty, it is in the same folder as the fla.

Do the following:

var newKey:KeyButton = new KeyButton();//Create the key button instance
addChild(newKey);//Add the keybutton to the display list

Remeber that KeyButton is also a movieclip, cause it extends MovieClip. So you have all the same functionality here.






0
keybordAuthor Commented:
Once again thanks for your help here.  I did manage to work this out eventually but thought I was doing something wrong because when I tried to attach the same script to each of the button movieclips flash wouldnt let me and requested 'a unique script not linked to an existing symbol'.  

Your last comments explain this and confirm what I thought which is that I would have to modify the class and save a separate class for each movie clip (as they are all slightly different - I just cant create instances of KeyButton).

So ultimately I feel like I am back at square one in that I have to effectively duplicate the class (like I was doing with my original functions) for each of my movieclips.  no worries though...I am very happy to be learning the ins and outs of classes!

I opened this as another question (that I think you have answered here!) so please head over and take the 'glory' ;o) you can find it here:

http://www.experts-exchange.com/Software/Photos_Graphics/Web_Graphics/Q_23116156.html

thank you
0
julianopolitoCommented:
Hi!

Well let me explain it to you in a better way.
OK, you can make a slight different class for each of your symbols, BUT , since you have the SAME functionality for all 6 buttons, lets do it another way, just keeping the same and only class.

Flash really needs a single identifier for each button, but you can have a different base class for the buttons and let flash create the identifiers for you. Do this:"

-Right Click the KeyButton movieclip in the library.
-Select Linkage...
-Check Export for Actionscript
-In the Base Class field, write KeyButton (it is case sensitive)
-In the Class field put something like KeyButton1 (change for each button, KeyButton2, 3,4 etc)
-Press OK button

This way, you will have the same Base Class for all buttons, and flash will create the other classes for you.





0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Graphics Software

From novice to tech pro — start learning today.