Removing Event Listeners
Hello!
I have a PopUpManager window that fires an event just before closing (not the CloseEvent).
I am listening for that event and handling it in a function.
Q: Is it best practice to remove the listener in the function that handles it or calling PopUpManager.removePopUp on that popup automatically does the "cleaning" as well?
Thank you!
Removing the eventListeners on a popup window is necessary I believe.
In your event handling function, you can remove the event listener by event.target.removeEventListener(..., ...). It doesn't matter that your component is handle by the popUpManager, you'll still have a reference to it.
Example
In main app:
var win:myClass = PopUpManager.createPopUp(this, myClass, true) as myClass;
win.addEventListener("myEvent", myHandler);
private function myHandler(evt:Event):void
evt.target.removeEventListener("myEvent", myHandler);
In custom myClass:
private function handleSomething(evt:Event):void
var ev:Event = new Event("myEvent");
dispatchEvent(ev);
if (isPopUp)
PopUpManager.removePopUp(this as IFlexDisplayObject);
Does this help?
Dany
Similar Messages
-
Removing Event Listeners - Are they needed all the time
My goal is to increase the performance of my project so I would like to know if it is always a good idea to remove event listeners. More specifically, lets say I have a movie with severals scenes and several frames within those scenes. Each one of the frames has an event listener:
Example:
Scene 1
Frame 1 (EventListener)
Frame 2 (EventListener)
Frame 3 (EventListener)
Frame 4 (EventListener)
Scene 2
Frame 1 (EventListener)
Frame 2 (EventListener)
Frame 3 (EventListener)
Frame 4 (EventListener)
Questions:
Does Flash continue to listen for an event in Scene 1/Frame 1 when the playhead has moved to Scene 1/ Frame 2?
Or does Flash just listen for the events when the playhead is in a particular frame only?
Should I remove the event listener once I leave a particular frame (should there be remove event listeners on each frame)?Just mentioning, the addEventListener comes with a parameter you can set to true or false called a weak reference. On desktop flash apps it can become time consuming to constantly remove listeners, especially when things drop off the display list frame to frame. You can mark them for automatic garbage collection by using the weak reference property.
e.g.
Credits_bnt.addEventListener(MouseEvent.CLICK, goCredits, false, 0, true); // set weak reference to true (e.g. remove when no references exist anymore automatically)
Eventually garbage collection will remove that reference automatically when there's nothing left on the display list or in memory to use it.
However, if this is targeted at mobile, you absolutely want to remove the reference as soon as possible when it's not needed for memory conservation. On a desktop it's not that big of a deal. -
Remove Event Listeners (at the right time)
I have a app which loads multiple flv's, I also have a timer
(digial) which shows how long the movie has been played for. The
problem is that whenever i load and new move (through the same
"loadVideos()" function, the timer variables ("lagTime", "endTime")
are not reset (even though the correct variables are being passed.
I believe it has something to do with the event listeners which are
being used to load the movies. How can i clear all the listerner
before reloading the movies?
Here is a code snippet:
Thanks in advanceThanks, kglad
Yes it traces 'endTime' but what happens is that when i play
the first movie is will display for example ("40,40,40,40" etc...)
until the video stops playing. If i load another movie it will then
trace ("40, 20, 40, 20, 40" etc...) so i need to kill the
listereners and reload the variables.
Jake -
Removing event listeners on leaving a frame
Hi team,
I am having a bit of trouble, I have l modded some code that I am really happy with, it makes buttons bounce around for the user to try to click on when entering a certain frame...
Problem.. I notice tha the code adds eventlisteners ENTER_FRAME to make this work, when you leave that frame there are now problems with null objects becuase the listeners are still on but the objects are not there anymore..
Ok so attempted solution - I can use a currentLabel on the main timeline to check if the correct frame is reached then use a function if (label is x) put listeners on else take them off... works but then I have to have these objects hidden on the timeline and then add visible=true/false to my framelabel listener.. This works but part of my functionality here is that these movieclips that move are buttons that the user clicks on and they explode and dissapear- but now they dont because I have a code that says on that frame they should be visible..
The only thing I can think of is to have a blank frame at the end of the explode and put a stop on it. Then add a gotoAndPlay(1) into my frame label code. Seems very ugly, you guys got a better way? Can I remove eventlisteners on leaving a frame? Is there a code like LEAVE_FRAME????
cheers
subyes, it goes in the keyframe where those movieclips exist. if the movieclips exist on a main timeline frame, that's where that code should be placed.
that code should execute when the movieclip exists. the listeners wait for the movieclips to be removed from the display list. that happens when you navigate away from the frame that contains those movieclips. -
Does removeChild remove the object's event listeners?
Hi
If you dynamically create a parent movieclip, and dynamically add a color picker to each clip, and add an event listener for each color picker, does a removeChild on the parent movieClip remove event listeners belonging to any of it's children?
Thanks
ShaunAhh - thanks Ned
Is there any software you could recommend that monitors and shows you what or how many event listeners are open, memory consumption etc, to help you to trim the fat from your coding?
Thanks
Shaun -
If you have multiple event listeners running, is there any way to remove all of them at once rather than one at a time?
Thanks,
JeffNear the end of the article linked below is one approach that someone has used involving an array:
http://www.almogdesign.net/blog/actionscript-3-event-listeners-tips-tricks/ -
Can't remove event listener from Image
I'm clearly missing something and would appreciate some help. I'm trying to run an event handler when an Image completes loading, then remove the handler so that it won't run again should the image be reloaded later.
The problem that I'm having is that the event handler simply wont' go away, despite calling removeEventListener on the Image object.
The following example demonstrates the problem (the example doesn't actually do anything useful...it's just the shortest example to demonstrate the problem). (To run the app, you'll have to provide any ol' JPEG file named "myImage.jpg" in the "src" directory of your project).
What I expect to happen is :
1) on startup, the image loads and loadComplete() runs.
2) loadComplete removes the event Listener so that subsequent re-loads won't re-fire the handler. I only want the handler to run once.
3) "loadComplete" shoudl be displayed in the Debug console.
4) A button click should display only "Changing Image" in the Debug console
What I get instead is that the loadComplete handler isn't removed, and every time I click the button, loadComplete runs when the image is re-loaded (i.e., every button click results in both "Change Image" AND "loadComplete" being displayed in the Debug console).
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Image width="655" height="181" source="myImage.jpg" id="myImage" autoLoad="true" scaleContent="true" complete="loadComplete()" x="100" y="100"/>
<mx:Button x="100" y="341" label="Button" click="click(event)"/>
<mx:Script>
<![CDATA[
private function loadComplete():void
trace ("loadComplete");
myImage.removeEventListener("complete", loadComplete);
private function click(evt:Event):void
trace ("Changing Image");
myImage.load("myImage.jpg"); // Reload same image; it's just an example
]]>
</mx:Script>
</mx:Application>Hi,
You can remove only event listeners that you added with the addEventListener() method in an ActionScript block. You cannot remove an event listener that was defined in the MXML tag, even if it was registered using a call to the addEventListener()method that was made inside a tag attribute.
Check this page for reference.
http://livedocs.adobe.com/flex/3/html/help.html?content=events_05.html
You can modify the code a bit a get it working
<mx:Image width="655" height="181" id="myImage" scaleContent="true"
x="100" y="100"
creationComplete="myImage_creationCompleteHandler(event)"/>
private function myImage_creationCompleteHandler(event:FlexEvent):void
myImage.addEventListener("complete",myImage_completeHandler);
myImage.load("myImage.jpg");
private function myImage_completeHandler(event:Event):void
myImage.removeEventListener("complete",myImage_completeHandler); -
Using Multiple Event Listeners
Hi,
I have a movielcip (A) class in which I have used a Tween class effect on a child movieclip (B) scrollRect. The (B) Movieclip in turn has several movieclips whose have tween class effect being executed on thier child movieclips.
the tweens are all unique to each movieclip
and the event listeners are taken off once completed.
This works all well and good in FLASH IDE...
My problem arises when I try to view this in a browser on a Windows XP
it doesnt work in
Opera Version 9.63
Firefox 2.0
and Google Chrome 2.0
The only browser it works fluently in is
Internet Explorer 7.0.5
What is happening in most cases it that the animation appears to "stick" but i think what may be happening is the listening or removal of the event listeners. The animations are left incompleted.
Is there any rule of thumb when using multiple event listeners?
here is a snippet of some of my code
on click event from movieclip (A)
private function scrollToSlidePrev(e:MouseEvent) {
if (((slideIndex - 1) >= 0)) {
nextButton.mouseEnabled = nextButton.enabled = previousButton.enabled = previousButton.mouseEnabled = false;
var position:Number = 0-SLIDEAREA.width;
var slide1:TileListSlide = slides[slideIndex] as TileListSlide;
var slide2:TileListSlide = slides[--slideIndex] as TileListSlide;
scrollSlide(position,slide1,slide2);
tween animation in movieclip (A) on (B)
private function scrollSlide(pos:int,slide1:TileListSlide,slide2:TileListSlide) {
slide1.resizeSlideTo(0.6); // execute tween on child movie clips in B
slide2.resizeSlideTo(1); // same as above;
var rect:Rectangle = sliderMc.scrollRect;
var tween1:Tween = new Tween(rect,"x",Regular.easeOut,rect.x,rect.x + pos,3,true);
tween1.addEventListener(TweenEvent.MOTION_CHANGE,setSliderScroll,false,4);
tween1.addEventListener(TweenEvent.MOTION_FINISH,toggleButtonEnabled,false,3);
tween animation in movieclip (B) children
public function resizeSlideTo(sc) {
var m:Matrix = tileList.transform.matrix as Matrix;
var p:Point = new Point (m.a, 0);
var tween2:Tween = new Tween(p,"x",Regular.easeOut,p.x,sc,3,true);
if (numericStepper != null) {
if (sc != 1) {
numericStepper.visible = false;
tween2.removeEventListener(TweenEvent.MOTION_FINISH,showStepper);
if (sc === 1) {
tween2.addEventListener(TweenEvent.MOTION_FINISH,showStepper,false,2);
tween2.addEventListener(TweenEvent.MOTION_CHANGE,setScaleOnScroll,false,3);
here is the link
http://visual_admin.web.aplus.net/ticker/ticker_widget.html
the effect disables and re-enables the buttons when its done.... then the listeners are removed.
each one with the exception cretes its own unique tween (obviously this is a custom class built as each clip)
i really don't know what to make of it guysapparantly making the tween a property of the class rather than a random variable in a function worked.....go figure
-
Loading/Unloading a .swf that adds event listeners to the Stage
Hi all,
Disclaimer
Apologies if I suck so bad at using forum search that the answer to this is on page 1 somewhere; I tried...
Question
I am loading and unloading a .swf to which I do not have source code access. This .swf places several event listeners on the stage, as far as I can tell. When the .swf is unloaded, the event listeners placed upon the stage still seem to be in effect. Using unloadAndStop doesn't seem to do it, and I have to target Flash Player 9, anyway, so can't really use it. Is there any other way I can keep this external .swf from holding onto my main movie's stage?
Additional info
All eventListeners and references being set by my code are removed.
I've managed a little contact with the author of the .swf:
I've requested he provide a dispose() method I can call to get all the listeners removed, and send an updated .swf.
He's suggested that I should be able to avoid the problem by loading into a unique ApplicationDomain. I'm not terribly familiar with this, but have given it a try without much success. Is this a valid solution - can I really protect my 'stage' by properly using ApplicationDomains - or do I need to persist in trying to get a public dispose() method built in?
Thanks in advance!
Cheers, Johnthanks for reply sir
sir actually, i have not any problem with loading any file but i need to go back to intro.swf file when i click on clsbtn of main.swf, i want unload the main.swf file and panel.swf file
actually i did was, i have intro.swf file and there is button by clicking load main.swf file (where is timeline controling butons) and in the main file automatically load panel.swf file ( where is all animation)
its all play gud , no problem
but my problem is there is a clsbtn in main.swf file and when i click on that button everything should be unload and it should return on the previous position in intro.swf
i hope u understand what i am trying to say -
Managing various event listeners in multi-frame movie
I'm working on a gunslinger game. I have numerous frames
which correspond to different stages of the game. The frame that
corresponds to the actual gameplay has a really involved
ENTER_FRAME function attached to particular item on the stage. When
the game is over (or an error occurs, or the network connection
fails) I want to leave the gameplay frame and move to some other
frame. When this happens, I would like the ENTER_FRAME function on
the gunslinger to be removed because the player may finish a game
and then re-enter the gameplay frame later after selecting a new
opponent.
QUESTION: Can anyone recommend a good way to manage the
keyboard event listeners, all the button event listeners, etc? As
you might imagine, I have no reliable way to determine which frame
might be entered after the gameplay frame because the frame change
could be triggered by a variety of different reasons.I have tried using hasEventListener to check for an existing
ENTER_FRAME function before adding the event listener again but it
never seems to notice that there is an existing enterframe function
running. Furthermore, when I leave the frame, the enterframe
function (which is attached to a particular movie clip on frame 2)
continues to run even though that movie clip doesn't exist on any
other frame in the flash movie.
The first frame in my movie just has a button that takes the
movie to frame 2. frame 2 has a movie clip (myMovie) and a button
(btnFrame1) which goes back to frame 1. It also has the attached
actionscript.
I start the movie.
I click 'goto frame 2'
the enterframe listener is added and starts to output trace
statements of the current frame of myMovie (e.g., 1-2-3).
i click 'goto frame 1' on the main movie
although i am looking at frame 1 of my main movie which has
no instance of myMovie, the enterframe function keeps tracing the
current frame--interestingly, the frame of myMovie does not
advance...it stays on 1, 2, or 3 and announces that frame over and
over again.
Repeating the visit to frame 1 and frame2 over and over again
results in more listeners being added over and over again.
I have uploaded a sample FLA here:
http://jaith.net/questions/listenerExample.zip
I hope that you might help me determine how to remove the
listener upon exiting this frame. I don't want that enterframe
function running (and referring to movieclips that don't exist)
when I exit the frame where it is relevant. I'm wondering if I
should try adding the event listener to the root movie
instead. -
Is there a way to clear ALL event listeners, stop all movie clips, etc?
Is there a syntax for this?
I have a movie that has 15 frames. Each frame has embedded movie clips within movie clips, tons of animations and event listeners. None is needed except when they are on the stage, on the frame. However, the animations continue even when the frame is left.
For instance, I have a frame that has a dynamically rendered animation of leaves falling from a tree. When the frame is left, the leaves continue to fall.
There are many instances of this type of thing happening.
Ideally, I would love to just be able to clear everything when a new frame is loaded, since none of the animations or event listeners need to carry over from one frame to another.
Is there a way to do this without the thousands of lines of code it would take to manually remove every single animation and event listener and sound, etc, from the stage?
Thanks so much!!
Amberyou have to manually do that.
or, you could convert each frame to a swf. load each swf when needed and, if you're publishing for fp 10+, you can apply unloadAndStop() to kill all streams in the loaded swf and ready those assets for gc. -
Memory cost of unremoved event listeners
Anyone have any insight into the memory usage of
eventlisteners in AS3, and whether allowing them to build up within
an application causes performance issues? Why isnt there a global
method that removes all listeners (or maybe there is?).
ThanksThank you kglad. It seems I stumbled upon an interesting
discovery today, and was wondering if you can confirm.
It appears that AS allows you to have duplicate
eventlisteners on objects. In other words, if you add 5 duplicate
listeners to an oject (e.g mc.addEventListener(MouseEvent.CLICK,
someFunction) x 5), then try to remove the event listener
(mc.removeEventListener(MouseEvent.CLICK, someFunction)), it is
only removing one of the event listeners right?
If that is the case, then can I do something like this to
remove them all? while (mc.hasEventListener(MouseEvent.CLICK)){
mc.removeEventListener(MouseEvent.CLICK, someFunction);
Thanks -
Help Removing events on a portion of the Display List
Hey all
Basically I'm looking for a "switch" that I can use to shut
of all events for a Display Object and all of its descendants in
the Flash display list / scene graph.
I have a Display Object with a good number of descendants
that have various MouseEvent listeners/handlers assigned to them.
I'd like to be able to remove/disable all of these mouse-related
events (or just all event types if thats easier) at a certain point
in time without knowing the number of descendants or how many and
which kind of event listeners have been registered with each node.
So apart from writing a unique event removal method for each
node, and then walking the Display List, calling this method for
each node, how do I do this? Rasterizing this display object to a
Bitmap object and then swapping the two in the display list to
obtain a "static" version with no handlers is a work-around I don't
really want to do either (sorry).
any ideas?For the mouse events, perhaps a combination of
DisplayObjectContainer.mouseChildren and
InteractiveObject.mouseEnabled -
Remove Event Listener : Best Practice
This quesiton isn't really keeping me from progressing on my current project, but I was wondering what the best practice was. If I'm about to remove an item with removeChild(), should I first remove any Event Listeners that were on that object or do those get removed and cleared from memory automatically when the child is removed?
Thanks,
DaveAs Kalisto mentioned, the listeners will only be removed automatically if you use weak reference when you add it:
myObject.addEventListener(MouseEvent.CLICK, someFunction, false, 0, true);
The true on the end specifies to use weak ref. If you don't use that (you always should) then you will have to remove it manually or it will hang around forever.
Also, removeChild simply removes the object from the display list... it's still in memory. Set it to null if you want to truly clear it. -
How to block execution of event listeners
Hi all,
JDev version : 11.1.1.6
My requirement is that I want to block all event listeners like ActionListeners, SelectionListeners, DisclosureListeners, RowDisclosure listeners when the screen is opened in readonly mode.
I could block ActionListeners by disabling command links and command buttons etc.
But there's no way to block SelectionListeners, DisclosureListeners, RowDisclosure listeners.
So Is there any common code which can block all listeners?
Or is there any EventController or something like that which will allow me to control event execution?I would have if it was just one screen.
There are hundreds of screens.
Anyways, can't I use any javascript to do this? There are some interfaces like EventListeners , classes like EventConsumer etc. Do none of them provide feature to block event listeners?
Maybe you are looking for
-
Can the Droid calendar and Outlook calendar on my home computer be synced?
-
Unexpected error (0xE8000001) when building in xcode
help, does anyone get this error message when they build in xcode, [device] and [debug]?
-
Ok this is my problem. I need to get a new browser window and i am using on (press) { getURL("file.swf", "_blank"); but for some rason it dose not oppend a new window it dose not do anything
-
Regarding BAPI_ACC_INVOICE_RECEIPT_POST
Hi, Using this BAPI BAPI_ACC_INVOICE_RECEIPT_POST i am able to create documents with out tax code population. but my requirement is i have to populate tax code, automatically calculate tax, payment referrence...etc. but i didn't find these fields in
-
Time Machine creates multiple sparsebundles on Airport Extreme
I recently started using a new hard drive for Time Machine, attached to my Airport Extreme (previous 250GB WD portable, now 1.5TB Seagate Freeagent). I never had any issues with the old drive, but have noticed a very weird problem on the new drive, a