What does addChild/removeChild do to memory in Actionscript 3? - actionscript-3

I'm unclear on how memory works in Actionscript 3. I create a series of buttons and store the address to each of them in an array. Those buttons are used to play various music files, and I want the one that is playing to have a particular color (red) and the rest to be white. I call the following code when the currently selected button is to be replaced by a different button:
removeChild(songSelectButton[currSong]);
var songSelWhite:Button = new Button(null, "images/TrackButtonNo.jpg", TRACK_SELECT_WIDTH, TRACK_SELECT_HEIGHT);
songSelectButton[currSong] = songSelWhite;
That allows the array to have the right buttons. However, I am concerned about whether I am wasting memory. Does garbage collection take care of this, or do I need a better approach?

In most cases, garbage collection is pretty smart and can clean up whatever mess you make. But it can take its time getting around to it, and it can really tie up the CPU when it decides to do it's thing. So careful management of memory is valuable.
In your case, why create a new Button? You've got a Button already, and it looks like its already in the right spot and everything. Just change the image, any listeners, and any other properties that you really need to change. Then you won't have to worry about new buttons getting allocated and deallocated, and you won't even have to worry about a new layout being calculated.

Related

actionscript 3: calling function for second time wont work

I'm new to actionscript 3, I have sequences of frames and two buttons to control which sequence to play, it first works properly, but have problem when a sequence is being played for the second time. I have used gotoAndPlay function for my navigation. can anyone help me?
From your description I have a hunch about what may be happening...
Firstly I would ask you if the buttons are present at all frames along the timeline? If they are not (ie, sometimes the timeline shows a frame where the buttons are not present before returning to them ) you should realise that when they come back into view again, they are not the same buttons as the ones from before. That means that the event listeners you attached the first time are not going to respond to clicks on these new buttons.
This happens because flash always totally recreates timeline objects when they come into view again. Flash can sometimes cope with a "jump" over a "gap" when a symbol is the same, but this is extremely unreliable and should be avoided for this reason.
You can avoid this problem by keeping the ui on the stage at all times, and revealing and hiding the buttons when you need them. Even better, create an instance of your ui in code and add it to the stage when you need it. This way you know there is only one instance, and you are in control of it.

use class to handle mutiple nested movieclips and their specific events

I have a menu with five buttons. Menu is visible all the time. there is click event for each menu item. which slides corresponding movie clip from left to right. each movie clip has different nature events and respective animation and activity. for example tab 1 brings the video page. and within that movie clip I have video events like play pause volume and on complete etc. events and code. tab 2 has button group for Time and another button group Features. depending on user selection code will calculate and show value on a animated counter. tab 3 has button group for Time and button group Source. as per the user selection it will calculate and show the values as animated graph. and so on.
Right now I have all the individual tab movie clip has its own time line code for its own events. and some crossover variables and references with other tabs. Everything is working as expected. No problem. I know time line code is not the best way to do any complex project.
So, I would like to get the entire coding as one class or more classes if that is the correct way.
I am beginner as far as class logic. I have already created Main as document class and could control the general navigation of tabs and their initial look. But stuck at tab specific button events and other such unique events for the specific tab.
Any help is greatly appreciated. Thanks in advance.
any similar example or suggestions.
First of all, thanks a lot for a prompt response. It seems like I am not even a beginner. I need to read a lot and probalbly grasp all fundamental concepts thoroughly. I have gone through both the links suggested in your comments. I am trying to digest the stuff slowly. I do not have any formal informal education regarding OOP or any sort of programming. To be honest, I have hard time understanding the code you have suggeted. Not because of your code but because of my level of caliber. I will have to spend some time to make myself clearer regarding events and sequence etc. different tab contents are as movieclips to main timeline and already placed on stage. It comes and goes to its corresponding tab button click event. I am not marking your answer as yes because I still need to my own homework based on your suggestion. Thanks a lot once again. I am sure I will ask few more questions later.
This is how I would design it:
I'd have a Menu Class, which only contains the buttons and "converts" clicks on them into more specific events. That might look something like this:
public Class Menu extends Sprite {
protected var buttons:Vector. = new Vector.();
public function Menu() {
super();
var loops:int = numChildren;
for (var i:int=0; i<loops; i++) {
var button:SimpleButton = getChildAt(i) as SimpleButton;
if (button) {
buttons[buttons.length] = button;
button.addEventListener(MouseEvent.CLICK, broadcastMenuEvent);
}
}
}
public function broadcastMenuEvent(e:Event):void {
var button:DisplayObject = e.currentTarget as DisplayObject;
dispatchEvent(new Event(button.name, true));//bubbling, can catch at any level
}
}
The way this is built, you can change the events that are being dispatched simply by changing the name you give the instance of the button on stage. Note that you need to apply Menu as the Base Class and not the Class for this to work if you have "declare instances automatically" unchecked, because doing it that way allows the compiler to generate those instance names for you in a way your base Class doesn't have to know about.
At this point, you can then deal with those events in another place--whether it's your main document Class or whether you have a separate Controller.
I would define each of the Views you described as a separate Class as well. If you have objects coming and going on the stage, you can use one of the techniques described here to handle that. Otherwise, it's fairly straightforward to address your timeline instances from the base Class instead of timeline code. Again, you can listen for those events in the main document Class or a dedicated Controller--the main point is to make sure your Views are not making any important decisions and usually they should not be editing data.
You can choose to have your Main Document orchestrate how the tabs get added and removed (I'm a big fan of using the timeline with goToAndStop, but not everyone shares this preference), or, again, you can separate this logic out to a dedicated Controller. I would suggest that if it's possible to generalize how your Views work to have them implement a single Interface. That way, you can give them a single instance name and manage them all with the same getter/setter pair (assuming you go the timeline route).
Note the Flash compiler isn't terribly sophisticated in this regard, so if you do this and your Views extend different parent Classes, you'll get compiler warnings. Just ignore these--they don't mean anything.
The thing you shoud try to root out of your code completely is the part where Views are referencing each other. The only time it's acceptable for one View to know about another is when it's a parent knowing about its child. Even then, try to have as little specific knowledge as possible. Notice in the Menu View I wrote as an example, the parent only knows there may be some SimpleButtons, but it has no specific knowledge of where they are on stage, what, specifically, is in them, or even what there instance names are.
Instead of having your Views know about one another, have a third party (which, again, you can choose to use the main Document Class for or not) that transfers requests for state changes (in the form of events) from one to another.

Basic MVC pattern communication

I just started to study the Model View Controller pattern. I now understand the basic usage of MVC, but when i tried to implement MVC in a simple test, i ran into a problem. Ofcoarse I could easily adjust the code so it works, but I wish to learn how to correctly implement the MVC pattern.
The test:
I used actionscript 3 to make a simple program. It consist of a turret, and a mouseclick. The turret is in the middle of the screen. When I click anywhere the turret rotates towards the point where I clicked. Both the mouse and the turret have their own model,view and controller. When I click, the MouseModel changes correctly. But for the actual TurretView to respond, the TurretModel must change its rotation variable and send out an event.
The question is who responds to the MouseModel event?
/------->MouseControl------\
/ \
MouseView ?<---MouseModel
TurretView <------------------TurretModel
TurretControl
I figured its best not to have MouseModel directly influence TurretModel or TurretControl, because this would require them to be an eventListener. Making TurretView listen to the MouseModel, and then tell TurretControl to adjust TurretModel, after wich TurretView can update trough a TurretModel event looks like a lot of extra code for a simple task. Also I'd rather not have MouseControl affect TurretModel, this would break the flexibility of the mouse as input for future classes.
Ow, also in which class do I put the code for the angle calculation?
Thanks in advance
Remember that the goal with MVC is primarily the separation of Model and View, and the Controller can serve as the communicator between the two.
Unless you are planning on storing each action that occurs (clicking, rotating, etc.), there is no real need for an action (in this situation) to send data to the Model. Everything you'd like to do should be easily handled with the Controller. So the flow would be:
Mouse click
Event is fired to trigger a command (in the Controller), passing along the mouse location
The command calculates the turret's rotation
The command tells the View to rotate the turret
This is, of course, my suggestion based off of your example. In truth, depending on the project, the above flow could easily change (for instance, in this situation it seems good to do rotation calculation in the command, but in other situations that may not make as much sense). Look at MVC as a goal - you're trying to separate these elements as much as possible, but there is no 100% "works-every-time" way to do it.
Robotlegs, a popular MVC framework, has a great diagram on their site showing how they tackled MVC:
http://www.robotlegs.org/diagram/
I'm not advertising that you NEED to use Robotlegs (it's good, but there's plenty of other alternatives), but they definitely made a pretty diagram :)
You should have one model, which then has pieces in it that you are currently calling MouseModel and TurretModel. You can either keep those names and breakdowns, or do something else once you have a better "handle" on what needs to be done.
The View that is tracking the mouse clicks should dispatch an event that your Controller component catches to update the TurretModel (at this point, there's probably no need for a MouseModel). Your TurretView can then update itself based on the TurretModel, or the Controller can update the TurretView based on the new value. This will depend on how you have it wired.
Usin a Framework such as Robotlegs can help you figure out all the ins and outs of this process, and I've heard that this book http://shop.oreilly.com/product/0636920021216.do provides a great explanation of MVC, even if you don't choose to use Robotlegs after you read it.

symbols placed on the timeline become undefined if stepping backwards

I am using the frames in the timeline of a .swf as pages in a flash app. The user can advance to the next page by clicking a button that takes her to the next frame. Similarly, it is possible to navigate to the previous frame/page as well.
Most of the content is placed on the stage (i.e. created by dragging an instance of a library symbol to the stage) but properties of those instances, such as .visible might be changed via actionscript. Also, some objects are loaded from external flash files and displayed programmatically with addChild / addChildAt.
The problem is, if I am on Frame N+1 and there is an object displayed on the stage programmatically (i.e. with addChild, not by having it placed on the stage) and navigate to Frame N where there is an object that is placed on the stage (i.e. dragged from the library),
then the instance of that object is undefined/null and throws an error if I try to set its properties (like .visible).
The error does not occur if I am moving to the NEXT frame, only if I am moving to the PREVIOUS one. Therefore I assume that some kind of initialization is not getting called while going one frame back.
I was also thinking that the objects would just not "live" to the next timeframe, that is, their value would be lost and re-initialized because of scope, but if there is no dynamically created object on the stage, I can navigate back and forth just fine.
Is there a way to ensure that the objects created on the stage do not disappear while navigating back to the previous frame?
The first, and more useful, part of the answer is this: timeline keyframes and scripts can give conflicting information about display objects - whether they should exist, where they should be, and so on. For example, when you add an item by playing into its frame, and then delete it with script, and then play into its frame again. When this happens, there's no unambiguously correct thing for Flash to do, so it tends to be unpredictable. I believe what generally happens is that once you fiddle with a given object via script, it's considered to no longer pay attention to the timeline - but your mileage will vary.
Having said that, the reason things are different when you play backwards is the second and more arcane part of the answer. Internally Flash functions differently when seeking forward and backwards on the timeline. Flash internally treats keyframes as changes to be applied in the forward direction, so as you play forward, it applies those changes in sequence. When you move backwards, however, from frame N+X to frame N, it doesn't scan through the intervening X frames reversing those changes - it jumps back to frame 1 and fast-forwards along to frame N. Normally, it amounts to the same thing and you don't need to worry about it, but when you get into the twitchy area where scripts and the timeline have a different idea of what should be on the stage, you're liable to see things behave differently depending on which way you jump (as you are now).
The super-short version is, for things to work predictably, try to ensure that any given object gets added, updated, and removed the same way - either all via script, or all via the timeline. When that seems impossible, fiddle with your content structure - usually, the best solution is to change your object into two nested ones, so that the things you want to do with script occur one level higher or lower than the things you want to do with the timeline.
I'm not sure I got your question right, but as3 does not instantiate elements on the timeline as soon as you gotoAndSomething, but later that frame.
That is, you can't
this.gotoAndPlay(10)
this.elementOnTimelineFrame10.DoSomething()
without errors.
I remember using this chunk of code in the past to work around this problem. It uses the Stage.Invalidate() function to wait for an Event.RENDER before trying to access and children, more info (although vague as hell) is here
private function init():void
{
stage.addEventListener(Event.RENDER, stage_renderHandler);
}
private function stage_renderHandler(evt:Event):void
{
// Run your code here
updateChildren();
}
private function enterFrameHandler(evt:Event):void
{
// triggers the RENDER event
stage.invalidate();
}
This also might me very costly (performance wise). I would strongly advise against dynamically adding/removing objects to an existing timeline, is there any way in which you can place an empty Sprite above the timeline animation and use that for all your dynamic content?
Hope this helps

AS3: strategy for adding sprites that animate sequentially

I am developing a component that can list files that users select from their filesystem. I'm using a (extended) FileReferenceList and (my own) FileReferenceDisplayList. The latter listens for events from the former.
If the FileReferenceDisplayList receives a FileReferenceListEvent.ADDED event, it should display the new item in the displaylist. However, when multiple files are added at once I want to animate them sequentially in stead of at the same time. What would be the best strategy for making sure the items are animated with small pauses between them?
I thought about putting newly added items in a queue and then polling the queue for existing items with an Event.ENTER_FRAME. But maybe you can suggest another method that doesn't need to make use of Event.ENTER_FRAME?
Edit
I guess I forgot to mention that the part that puzzles me the most how I can set some timeout if multiple files are added. Maybe I should use the queue's length to multiply the timeouts for the items? So, if a file is added, I set the animation timeout for that item to be multiplied by the current length of the queue? (Just thinking out loud here).
take a look at TimeLineLite from Greensock - http://blog.greensock.com/timelinelite/
insertMultiple() and appendMultiple()
provide some very powerful sequencing
tools, allowing you to add an Array of
tweens or timelines and optionally
align them with SEQUENCE or START
modes, and even stagger them if you
want.
You can use a Timer but why not stick with the ENTER_FRAME.