EventListeners

Hi all,
I have been testing today with Eventlisteners in CS3.
Can't figure out the logic of it. I have the code below:
#targetengine "session"
main();
function main(){
var myApplicationEventListener = app.eventListeners.add("afterOpen", myEventInfo, false);
function myEventInfo(myEvent){
alert(myEvent.currentTarget.documents.length);
app.activeDocument.textFrames.add();
The thing is that the alert says that there is 1 document open,
but when I want to do something with this doc I get an error message
that there is no open document.
Can someone help with this?
Thanks Michel

I recommend reading another post about Eventlistener that I was involved in (
Alexandre VERCAMMEN, "(CS3) Does anyone know how to place request for..." #, 7 May 2008 12:42 pm). Regarding the close statement, with the help of Olev, we went the option of menu.actions. Please note the limitations (which a + in my case) of closing the doc. by closing the window.
At Startup I run the following script. FYI: A lot of my scripts are triggered Manualy or by Menu Actions, therefore a few GLOBAL vars. Also it adds flexibility when installed for different machines.
The Function EventOpen DOES NOT WORK when associated to app.eventListener, it crashes InDesign when closing the document! But it does work when triggered manually or by menu.
#target indesign
#targetengine "session"
app.scriptPreferences.version = 5.0;
//*** Initialize GLOBAL Variables
app.scriptArgs.clear();
app.scriptArgs.set("Event_Path", myScriptPath); //***Path to InEventScript Plug-In
app.scriptArgs.set("Event_Open", myScriptPath + "/PrePressOPEN.jsx");
app.scriptArgs.set("Event_Close", myScriptPath + "/PrePressCLOSE.jsx");
app.scriptArgs.set("Event_Copy", myScriptPath + "/PrePressCOPY.jsx");
app.scriptArgs.set("Event_Clean", myScriptPath + "/PrePressCLEAN.jsx");
app.scriptArgs.set("Event_Print", myScriptPath + "/PrePressPRINT.jsx");
app.scriptArgs.set("Event_App", myScriptPath + "/PrePressAPPPreferences.jsx");
app.scriptArgs.set("Event_Doc", myScriptPath + "/PrePressDOCPreferences.jsx");
//******************** ACTIONS ********************
app.menuActions.item("Open...").addEventListener("afterInvoke",EventOpen, false);
app.menuActions.item("Close").addEventListener("beforeInvoke",EventClose, false);
app.menuActions.item("Copy").addEventListener("afterInvoke",EventCopy, false);
app.menuActions.item("Paste").addEventListener("afterInvoke",EventClean, false);
app.menuActions.item("Print...").addEventListener("beforeInvoke",EventPrint, false);
//****************** FUNCTIONS Definitions ********************
function EventOpen (itsEvent)
var myExeSrcFile = new File (app.scriptArgs.get("Event_Open"));
if (myExeSrcFile.exists)
myExeSrcFile.open ('r:(read)');
app.doScript(myExeSrcFile, ScriptLanguage.javascript);
myExeSrcFile.close();
else
alert ("Error! Missing File:\n\n" + myExeSrcFile.fsName);
return;
function EventClose (itsEvent)
var myExeSrcFile = new File (app.scriptArgs.get("Event_Close"));
if (myExeSrcFile.exists)
myExeSrcFile.open ('r:(read)');
app.doScript(myExeSrcFile, ScriptLanguage.javascript);
myExeSrcFile.close();
else
alert ("Error! Missing File:\n\n" + myExeSrcFile.fsName);
return;
function EventCopy (itsEvent)
var myExeSrcFile = new File (app.scriptArgs.get("Event_Copy"));
if (myExeSrcFile.exists)
myExeSrcFile.open ('r:(read)');
app.doScript(myExeSrcFile, ScriptLanguage.javascript);
myExeSrcFile.close();
else
alert ("Error! Missing File:\n\n" + myExeSrcFile.fsName);
return;
function EventClean (itsEvent)
var myExeSrcFile = new File (app.scriptArgs.get("Event_Clean"));
if (myExeSrcFile.exists)
myExeSrcFile.open ('r:(read)');
app.doScript(myExeSrcFile, ScriptLanguage.javascript);
myExeSrcFile.close();
else
alert ("Error! Missing File:\n\n" + myExeSrcFile.fsName);
return;
function EventPrint (itsEvent)
var myExeSrcFile = new File (app.scriptArgs.get("Event_Print"));
if (myExeSrcFile.exists)
myExeSrcFile.open ('r:(read)');
app.doScript(myExeSrcFile, ScriptLanguage.javascript);
myExeSrcFile.close();
else
alert ("Error! Missing File:\n\n" + myExeSrcFile.fsName);
return;

Similar Messages

  • [JS](CS3) More EventListeners...?

    I was wondering if they were more EventListeners. I am specifically looking more "Copy" & "Paste" and their specifics "Before " & "After".
    Also,
    1) What is the difference between [var xxx = app.eventListeners.add(...);] and [app.eventListeners.add(...);]. They both add the event. Obviously one has a pointer to the event. But how usefull is it when the event is associated to a function or pointing to a file to execute? I can't imagine the pointer to the event bein "manipulated" after the event has been defined (var xxx = ...).
    2) Is the event "afterOpen" not supposed to trigger AFTER the document is opened? I have defined the event to execute a file and the script alerts me of "No Document Opened!!!". I understand the use of [event.parent] but that forces me to double the scripts that are tied to eventListeners. One regular version using app.activeDocument (accessable w/i User/Script Panel) & a modified version using event.parent (defined in the Startup Script). Are my assumption correct?
    Any help appreciated, Alex.

    Thanks, Harbs and Dave!
    Before I saw your answers I came up with a (longer) solution:
    var storyRef = app.activeDocument.stories;
    var arrStories = [];
    for(var j = 0; storyRef.length > j; j++){
        arrStories.push(storyRef[j])
        }//end for
    var arrParas2 = [];
    for(var x = 0; arrStories.length > x; x++){
        for(var y = 0; arrStories[x].paragraphs.length > y; y++){
            arrParas2.push(arrStories[x].paragraphs[y]);
            }//end for y
        }//end for x
    But I am curious about something. Your solution and my solution both result in an array of all paragraphs in the document but the data browser shows these arrays in different ways. I am wondering how to intrepret them.
    Your solution does not show the indexed paragraphs, mine does. See the images below.
    Your solution:
    My solution:

  • Best practice for adding and removing eventListeners?

    Hi,
    What is the best practice in regards to CPU usage and performance for dealing with eventListeners when adding and removing movieclips to the stage?
    1. Add the eventListeners when the mc is instantiated and leave them be until exiting the app
    or
    2. Add and remove the eventListeners as the mc is added or removed from the stage (via an addedToStage and removedFromStage listener method)
    I would appreciate any thoughts you could share with me. Thanks!
    JP

    Thanks neh and Applauz78.
    As I understand it, the main concern with removing listeners is to conserve memory. However, I've tested memory use and this is not really an issue for my app, so I'm more concerned if there will be any effect on CPU (app response) if I'm constantly adding and removing a list of listeners every time a user loads an mc to the stage, as compared to just leaving them active and "ready to go" when needed.
    Is there any way to measure CPU use for an AIR app on iOS?
    (It may help to know my app is small - I'm talking well under 100 active listeners total for all movieclips combined.)

  • Too many eventListeners in nested form causes falsh cs6 debugging session to crash ?

    Hello all !
    The above video (http://www.youtube.com/watch?v=53vqkd5VLFw) is that of a simple sequential click game. The code works perfectly in a simple situation of just nine movieclips or even upto 20 movieclips or so. But when i increase the numbers of movieclips further and adds more eventlisteners in nested form, the flash cs6 debugging sessions seems to get overloaded and fails to give a result. It simply gets hanged.
    Working Code for a simple situation:
    startBtn.addEventListener(MouseEvent.CLICK, trigGame)
    function trigGame(e:MouseEvent):void{
    //n1 to n9 are the nine movieclips arranged in grid form
    n1.alpha = 1;          n2.alpha = 1;          n3.alpha = 1;
    n4.alpha = 1;          n5.alpha = 1;          n6.alpha = 1;
    n7.alpha = 1;          n8.alpha = 1;          n9.alpha = 1;
    startBtn.visible = false;
    //GRID SHUFFLE CODE:OPEN
    function randomSort(a:*, b:*):Number
        if (Math.random() < 0.5) return -1;
        else return 1;
    var positions:Array = [new Point( 158, 296),new Point(238, 296),new Point(318,  296),
    new Point( 158, 366),new Point( 238, 366),new Point( 318, 366),new Point(158, 436),
    new Point( 238,436),new Point(318, 436)];
    var mcs:Array = [n1,n2,n3,n4,n5,n6,n7,n8,n9];
    positions.sort(randomSort);
    var q:int = positions.length;
    for(var t = 0; t < q; t++)
        var mc:MovieClip = mcs[t];
        var point:Point = positions[t];
        mc.x = point.x;
        mc.y = point.y;
    //GRID SHUFFLE CODE:CLOSE
    {n1.addEventListener(MouseEvent.MOUSE_DOWN, alph1);
    function alph1(e:MouseEvent):void
    {{n1.alpha = .5;n1.removeEventListener(MouseEvent.MOUSE_DOWN, alph1);};
    n2.addEventListener(MouseEvent.MOUSE_DOWN, alph2);
    function alph2(e:MouseEvent):void
    {{n2.alpha = .5;n2.removeEventListener(MouseEvent.MOUSE_DOWN, alph2);};
    n3.addEventListener(MouseEvent.MOUSE_DOWN, alph3);
    function alph3(e:MouseEvent):void
    {{n3.alpha = .5;n3.removeEventListener(MouseEvent.MOUSE_DOWN, alph3);};
    n4.addEventListener(MouseEvent.MOUSE_DOWN, alph4);
    function alph4(e:MouseEvent):void
    {{n4.alpha = .5;n4.removeEventListener(MouseEvent.MOUSE_DOWN, alph4);};
    n5.addEventListener(MouseEvent.MOUSE_DOWN, alph5);
    function alph5(e:MouseEvent):void
    {{n5.alpha = .5;n5.removeEventListener(MouseEvent.MOUSE_DOWN, alph5);};
    n6.addEventListener(MouseEvent.MOUSE_DOWN, alph6);
    function alph6(e:MouseEvent):void
    {{n6.alpha = .5;n6.removeEventListener(MouseEvent.MOUSE_DOWN, alph6);};
    n7.addEventListener(MouseEvent.MOUSE_DOWN, alph7);
    function alph7(e:MouseEvent):void
    {{n7.alpha = .5;n7.removeEventListener(MouseEvent.MOUSE_DOWN, alph7);};
    n8.addEventListener(MouseEvent.MOUSE_DOWN, alph8);
    function alph8(e:MouseEvent):void
    {{n8.alpha = .5;n8.removeEventListener(MouseEvent.MOUSE_DOWN, alph8);};
    n9.addEventListener(MouseEvent.MOUSE_DOWN, alph9);
    function alph9(e:MouseEvent):void
    {{n9.alpha = .5;n9.removeEventListener(MouseEvent.MOUSE_DOWN, alph9);};
    {startBtn.visible = true}
    Can anyone please help.
    Thanks in advance
    with best regards
    shams

    @kglad
    i have copied and pasted the code as given below. Can you please point out
    if there is anything that needs to be completed. Or rather, how can i
    complete the "if" statement:
    var positions:Array = [new Point( 158, 296),new Point(238, 296),new
    Point(318,  296),
    new Point( 158, 366),new Point( 238, 366),new Point( 318, 366),new
    Point(158, 436),
    new Point( 238,436),new Point(318, 436)];
    var errors:int;
    var mcs:Array = ;
    startF();
    function startF():void{
    errors=0;
    shuffle(positions);
    for(var i:int=0;i<positions.length;i++){
    mcs[i].addEventListener(MouseEvent.MOUSE_DOWN,downF);
    mcs[i].x=positions[i].x;
    mcs[i].y=positions[i].y;
    mcs[i].alpha=1;
    function downF(e:MouseEvent):void{
    if(mcs.indexOf(e.currentTarget)==0 ||
    mcs[mcs.indexOf(e.currentTarget)-1].alpha<.8){
    e.currentTarget.alpha=.5;
    e.currentTarget.removeEventListener(MouseEvent.MOUSE_DOWN,downF);
    if(mcs.indexOf(e.currentTarget)==mcs.length-1){
    gameoverF();
    } else {
    errors++;
    function gameoverF():void{
    // display congrats if errors 0 or some other low number
    // when you want to restart the game, call startF().
    function shuffle(a:Array) {
        var p:int;
        var t:*;
        var ivar:int;
        for (ivar = a.length-1; ivar>=0; ivar--) {
            p=Math.floor((ivar+1)*Math.random());
            t = a[ivar];
            a[ivar] = a[p];
            a[p] = t;
    thanks a lot

  • EventListeners in Illustrator CS2

    Hi All,
    I have created eventListeners in InDesign, when i am trying to create in illustrator it doesn't work. What was the problem behind with this.
    Please anyone help me.
    Arivu

    Mark,
    I don't have CS2 installed anywhere to try it, but I don't recall having seen any mention that ScriptUI dialogs and palettes will not work in CS2. You could try running my JET_RandomPatchworkSphere script here as a test.
    JET

  • AS3: DisplayList and EventListeners

    I was wondering if there's a way to monitor the DisplayList
    so that you can see when items get removed/Garbage Collected.
    And is there a way to monitor EventListeners so that you can
    see if you're effectively removing them when they're no longer
    needed?
    Thanks...
    Brenda

    you can monitor the display list but that doesn't make much
    sense in the present context: if you want something gc'd, it must
    be removed from the displaylist. you surely won't detect something
    being gc'd by monitoring the displaylist.
    in general, you must know to what displayobjectcontainer you
    added your display object or you can't remove it. and if you know
    that, you must use removeChild() or removeChildAt() to remove it.
    you could check the numChildren property of your
    displayobjectcontainer, but that would be a pretty crude way to
    determine if a particular object has been removed from that
    displayobjectcontainer.

  • Errortrapping failing eventlisteners

    ls,
    I made a virtual touch joystick that uses up/down/left/right mc mousedown/touch eventlisteners.
    In addition, i placed a mouse/tpuch move listener over it so it keeps track of dragging fingers over it.
    Works great. but.
    Appearantly, very now and then, some eventlisteners seem to fail and the joystick stops responding to individual touches.
    The touch move still operates so clicking/tapping and moveing will stil register as an event but the tap/click itself is ignored.
    This only happens on the device itself and its so random  i have failed to trap it using debugging.
    To solve this I was hoping to be able to trap an error on a listener and then remove and renew it.
    Is this possible?
    Regards,
    Mac

    Thanks Colin,
    As far as I am aware the structure is
    stage/MovieClip1("card")/textBoxes(including "txtEquation") and
    stage/MovieClip2("console")/buttons.
    I have just tried putting the following into the function
    called by a button's eventWatcher:
    var newEquationText:String =
    MovieClip(parent).card.txtEquation.text;
    trace(newEquationText);
    Is my structure not as I'd thought?
    Cheers
    Dougal
    ... and it's thrown up "TypeError: Error #1034: Type Coercion
    failed: cannot convert flash.display::Stage@1dcab461 to
    flash.display.MovieClip. at
    quiz_fla::MainTimeline/Next_card()"

  • Chaining of eventListeners BUGS with Loader

    My goal is to load numerous images to be displayed in an AIR application. For this I use the following code. The counter counts the number of times each event is triggered. The problem is that loading 1024 images:
    -  in the onLoadingComplete function the counter finishes at 1024... this is fine
    -  in the onParsingComplete function the counter finishes at various numbers (412, 405, 380...) different at each run
    - nothing goes wrong with less than around 500 images, all are loaded
    My assumptions:
    - 'complete' event not triggered if image content is the same (I am using 8 copies of 128 different images)
    - loaders have a concurrency problem
    - eventListeners asynchronous behavior is buggy
    ANY IDEAS, FEEDBACK ? Should I file a bug ? (by the way I am using Flex 4 on a mac)
    for each( var file: File in files ) {
         if ( ! file.isDirectory && file.extension == "jpeg" || file.extension == "jpg" || file.extension == "png" ) {
         var urlLoader: URLLoader = new URLLoader( );
         urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
         urlLoader.addEventListener(Event.COMPLETE, onLoadingComplete );
            urlLoader.load( new URLRequest(file.url) );
    private function onLoadingComplete( e: Event ):void
         var dispLoader: Loader = new Loader( );
         dispLoader.contentLoaderInfo.addEventListener( Event.COMPLETE, onParsingComplete);
         dispLoader.loadBytes( e.target.data );
         //counter++ --> here end up with counter = 1024
    private function onParsingComplete( e: Event ):void
         var img: BitmapImage = new BitmapImage( );
         img.source = (e.target.content as Bitmap).bitmapData;
         _images.push( img );
         counter++; --> here end up with counter = 412, 405, 512 or in debug mode around 380

    I've been doing a batchLoader loading batch of 100 images every 2sec... and it works; so it seems that when there is too many eventListeners running, they get ignored. I will need to do a more robust workaround for this, but...
    Here is a code snipplet:
    private var files:Array;
    private var offset:int = 0;
    private const BATCH:int = 100;
    var timer:Timer = new Timer(2000, Math.ceil(files.length/BATCH));
    timer.addEventListener(TimerEvent.TIMER, batchLoad);
    timer.start();
    private function batchLoad(e:TimerEvent):void {
              var file:File;
              var urlLoader: URLLoader;
              for (var i:int=offset; i<offset+BATCH && i<files.length; i++)  {
    //                    for each( var file: File in files ) {
              file = files[i];
              if ( ! file.isDirectory && file.extension == "jpeg" || file.extension == "jpg" || file.extension == "png" ) {
                   urlLoader = new URLLoader( );
                   urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
                   urlLoader.addEventListener(Event.COMPLETE, onLoadingComplete );
                   urlLoader.load( new URLRequest(file.url) );
                   counter++;
         trace ("counter: "+counter);
         offset += BATCH;

  • GetImageReference and eventListeners

    Hi,
    Through a textField you can access images (or it's Loader
    object) with
    getImageReference( imgId ). This works fine.
    Now I want to add eventListeners to the Loader to detect
    mouseClicks on
    the images. But somehow that part won't work.
    Code from a quick test:
    In a function which loads the XML I have these lines:
    var img:Loader = Loader( html_txt.getImageReference( "img_0"
    img.contentLoaderInfo.addEventListener( Event.COMPLETE,
    loadedImage );
    the eventListeners are:
    function clickImage( evt:MouseEvent ):void
    trace( evt.target );
    function loadedImage( evt:Event ):void
    trace( evt.target.content, "is loaded" )
    var li:LoaderInfo = LoaderInfo( evt.target );
    li.content.addEventListener( MouseEvent.CLICK, clickImage );
    li.loader.addEventListener( MouseEvent.CLICK, clickImage );
    Al this traces:
    [object Bitmap] is loaded
    If I click on tha image in the textField however, nothing
    happens... Now
    I could go with the textField, have it listen to mouseEvents,
    get the
    bounds of all the images in it and see over which the mouse
    is at that
    moment, but that seems rather silly if I could get each image
    to
    register it's own listeners.
    Anybody?
    Thanks in advance.
    Manno
    Manno Bult
    http://www.aloft.nl

    Hi kglad and others,
    well, it works, but not as intended (at least, not my
    intention ;) ).
    addChild( img ); adds the image to the root (or parent of the
    textField) thereby removing it, like documentation states, from the
    textField itself. Ok, it becomes clickable, but not as part of the
    content of the textField.
    You cant issue addChild() on the textField in anyway so that
    won't work.
    Has anyone been able to do sort of the same thing as I'm
    trying now?
    Below is some simplified code working on this XML:
    <?xml version="1.0" encoding="utf-8"?>
    <rootnode>
    <p>Lorem ipsum... </p>
    <img src="plaatje.jpg" id="img_0" />
    <p>Donec malesuada, arcu eget tristique convallis...
    </p>
    </rootnode>
    Thanks,
    Manno

  • ExtendScript eventListeners (For CC Mac 9.x)

    Hello Everyone:
       Okay, okay it's probably my aged gray matter that is causing such difficulty but after six months of dealing with Javascript eventListeners I still don't get them.  Does anyone know of a good tutorial/reference that will help this poor fading programmer figure them out.
       I do not have a specific question; I only know that current documentation does a very poor job of providing a complete reference in one place if one is trying to learn about event listeners.
    R,
    John

    PM-Apple,
    Have you checked out the following web page? It is the best starting point after the shipping examples that use Apple Events with Excel. I also tried to search Google for other examples (I didn't find any others on NI's site) and I found a few free trials of software that use LabVIEW and Apple Events. Try that search and see what you find. I am very sorry that I have not been as much help as I would like to be.
    Using Apple Events and the PPC Toolbox to Communicate with LabVIEW Applications on the Macintosh
    Randy Hoskin
    Applications Engineer
    National Instruments
    http://www.ni.com/ask

  • Multiple EventListeners, modulus and rotating cubes... performance issues.

    Hi.
    I've created a grid of 3D cubes using modulus, and the 3d cubes are were created from the Math and Flash Tutorial, if you are interested it is here http://www.flashandmath.com/advanced/menu3d/.
    What  I am trying to accomplish (and it works, just the performance is lousy). All the cubes in the grid are inactive until the mouse hovers over them, then they start to rotate, and once the mouse moves off them they continue to rotate.
    Time for the script:
    To create I create the grid like this:
    public function FlowerMenu(){
    var rowY:Number = 0;
    for (var i:int = 0; i < 190; i++) {
         var myCube = new               CubeMenu(["anemon.jpg","parodia.jpg","anagallis.jpg","lila.jpg","cosmos.jpg","adonis.jpg" ],100);
         myCube.x = 0 + ((i % 10) * 200);
         if (i % 10 == 0) {
             rowY += 200;
    myCube.y = rowY;
    addChild(myCube);
    That works fine, although if anybody has any improvements I would  appreciate them.
    And now for the mouse events & event listeners:
    private var i:int = 0;
    private function setUpListeners():void
        spBoard.addEventListener(MouseEvent.MOUSE_OVER, boardOver);
        spBoard.addEventListener(MouseEvent.MOUSE_OUT, boardOut);
    private function boardOver(e:MouseEvent):void
        addEventListener(Event.ENTER_FRAME, rotateSquare);
    private function boardOut(e:MouseEvent):void
        addEventListener(Event.ENTER_FRAME, rotateSquare);
    private function rotateSquare(e:Event)
        renderView(curTheta+i, curPhi+i);
        i++;
    So, this works, but after about 4 or 5 cubes have started rotating the
    performance drops considerably. I can imagine creating that many
    EventListeners isn't a good idea, but I can't see any other way of
    doing it.
    Does anybody have any suggestions or code improvements, I'm very new to AS3
    and Flash so any help or suggestions would be greatly appreciated.
    Thanks in advance.

    Actually I'm not using paper vision, I'm using the source from flash and math's using transformation matrixes and bitmaps here http://www.flashandmath.com/advanced/menu3d/index.html
    No, the boardOut function, is for when the mouse rolls off the cube, it starts it spinning indefinitely.
    private function boardOut(e:MouseEvent):void
        addEventListener(Event.ENTER_FRAME, rotateSquare);
    If it helps I could post the project in a zip, so you can get an idea of what it is, i'm doing and can see where the performance hit is. Is there any recognised  method of doing this on boards?

  • Should eventListeners always be removed before executing it again?

    Hi there,
    Should you always remove eventListeners before you want to
    execute it again?
    The reason why i ask this, is because in AS 2, i remembered
    that when you used
    a listener to a key and you go to another frame ..and go back
    to the frame where the listener is
    instantiated it listens twice! So when you press the key
    once, it will listen two times.
    And when using an addEventListener within a function like
    this:
    function startListening() {
    var loader:URLLoader = new URLLoader();
    loader.addEventListener(Event.COMPLETE, completeHandler);
    can you use outside this function another function to remove
    this listener like this?
    function removeListening() {
    loader.removeEventListener(Event.COMPLETE, completeHandler);
    Or do you have to scope the line: var loader:URLLoader = new
    URLLoader(); outside the function
    to remove this eventListener?
    I am trying to understand what is the best way and why.
    Does anyone have some tips what the best way is?
    Please keep in mind that i switch from different frames. So
    when i go back to the first frame all code
    is executed again.
    And is there a way to remove an EventListener without being
    sure if it exists?
    Something like:
    if(loader.addEventListener!=null) {
    loader.removeEventListener(Event.COMPLETE, completeHandler);

    If you instantiate a variable inside a function, then the
    scope of that variable is only inside this one function. So, trying
    to remove the eventListener from outside the function will result
    in an error. If you declare the loader variable outside the
    function, then you can assign the eventListener in a function.
    Likewise, you can remove the eventListener from another function.
    If you place all of your functions in the first frame of your
    movie's timeline, you won't need to worry about duplicating
    function calls.
    As an example, paste the following code into a new empty
    movie's frame script space. Extend the timeline to about 20 frames.
    Play the movie. You'll see that the ouput window shows the number 1
    each time the movie loops. The number does not increment. Each time
    the movie loops through the first frame, the variable is reset to 0
    and then incremented to 1.

  • EventListeners, bindingUtils, garbageCollection and you...

    Hey everyone,
    I hope somewhere can help me with this, because I have been
    running in circles on this. I am developing on a fairly large
    application and have recently noticed that instances of my class
    that have event listeners of data binding tied to them cannot be
    garbage collected. It has led to some fantastically bizarre
    artifacts and some gross memory leaks. Multiple copies of screens
    modifying and accessing the same array collections and such...fun.
    The way I see it, there are three real solutions here...
    1.) dictate that all programmers declare weak references when
    creating event listeners
    2.) create some sort of onDestroy method that kills bindings
    and removes eventlisteners when a child is removed from it's parent
    3.) override the addEventListener method to ensure that weak
    references are made, when people inevitable forget #1!
    My questions are thrice: are those my only options?! Or have
    any of you more experienced folks conquered this situation in a
    more elegant, reliable way? If these are my only options, which is
    the best, in your opinions?
    Thank you very much for any info you can give; I'm relatively
    new to Flex and while I understand the GC's terms and conditions,
    I'm hoping there is some way to avoid a massive rewrite/refactoring
    to make it work with me. Thanks again!
    -=Bill

    "bill.cabral" <[email protected]> wrote in
    message
    news:gdqvng$cav$[email protected]..
    > Hey everyone,
    >
    > I hope somewhere can help me with this, because I have
    been running in
    > circles
    > on this. I am developing on a fairly large application
    and have recently
    > noticed that instances of my class that have event
    listeners of data
    > binding
    > tied to them cannot be garbage collected. It has led to
    some
    > fantastically
    > bizarre artifacts and some gross memory leaks. Multiple
    copies of screens
    > modifying and accessing the same array collections and
    such...fun. The
    > way I
    > see it, there are three real solutions here...
    >
    > 1.) dictate that all programmers declare weak references
    when creating
    > event
    > listeners
    > 2.) create some sort of onDestroy method that kills
    bindings and removes
    > eventlisteners when a child is removed from it's parent
    > 3.) override the addEventListener method to ensure that
    weak references
    > are
    > made, when people inevitable forget #1!
    >
    > My questions are thrice: are those my only options?! Or
    have any of you
    > more
    > experienced folks conquered this situation in a more
    elegant, reliable
    > way? If
    > these are my only options, which is the best, in your
    opinions?
    >
    > Thank you very much for any info you can give; I'm
    relatively new to Flex
    > and
    > while I understand the GC's terms and conditions, I'm
    hoping there is some
    > way
    > to avoid a massive rewrite/refactoring to make it work
    with me. Thanks
    > again!
    There aren't any easy answers, but this might point you in
    the right
    direction:
    http://link.brightcove.com/services/player/bcpid1733261879?bclid=1729365228&bctid=17412126 60
    Keep in mind that any event listeners added within the scope
    of a component
    will be destroyed when the component is destroyed.
    so this.addEventListener=OK
    that.addEventListener=may not be
    HTH;
    Amy

  • Is it possible to pass parameters through eventlisteners?

    Hello everyone!
    Inside a .fla file I have some buttons and each button will tween a different image to the stage. All the images are outside the stage in the same x and y position and I just need to tween the x coordinate.
    Now I'm working with an external document class where I'm trying to hold all my functions and I'm stucked with the Tweens. I'm willing to stay away from the flash tween engine and I'm trying to work with tweenLite.
    My question is: Is it possible to pass parameters through eventListeners so I can use something like this inside my docClass?
         public function animeThis (e:MouseEvent, mc:MovieClip, ep:int):void { //ep stands for endPoint.
         TweenLite.to(mc, 2, {x:ep});
    If this is possible, how am I supposed to write the listeners so it will pass the event to be listened for AND those parameters? And how to build the function so it will receive those parameters and the event?
    If this is not possible, what's the best approach to do this?
    Thanks again!

    So, I understand you need to match buttons with corresponding visuals.
    Here is a suggested approach.
    Since SimpleButton is not a dynamic class, I suggest you have an enhanced base class for these buttons that extends SimpleButton. What is enhanced is that button has reference to the target.
    I wrote code off the top of my head and it may be buggy. But concept is clear:
    This is base class for all the buttons:
    package 
         import flash.display.DisplayObject;
         import flash.display.SimpleButton;
         public class NavButton extends SimpleButton
              public var targetObject:DisplayObject
              public function NavButton()
    Now, this is your doc class that utilizes this new buttons:
    package 
         import flash.display.DisplayObject;
         import flash.display.MovieClip;
         import flash.display.Sprite;
         import flash.events.Event;
         import flash.events.MouseEvent;
         public class DocClass extends Sprite
              private var btnArray:Array;
              private var visuals:Array;
              // references to objects being swapped
              private var visualIn:MovieClip;
              private var visualOut:MovieClip;
              public function DocClass()
                   if (stage) init();
                   else addEventListener(Event.ADDED_TO_STAGE, init);
              private function init(e:Event = null):void
                   removeEventListener(Event.ADDED_TO_STAGE, init);
                   // buttons and MCs shouldn't be in the same array - otherwise it is counterintuitive
                   // assuming all the objects are on stage
                   btnArray = [price_btn, pack_btn, brand_btn, position_btn];
                   visuals = [g19_mc, g16_mc, g09_mc, g04_mc];
                   configObjects();
              private function configObjects():void
                   var currentVisual:MovieClip;
                   var currentButton:NavButton;
                   for (var i:int = 0; i < btnArray.length; i++)
                        currentVisual = visuals[i];
                        // hold original positioin
                        currentVisual.hiddenPosition = currentVisual.x;
                        currentButton = btnArray[i];
                        // set target MC
                        currentButton.targetObject = currentVisual;
                        currentVisual.addEventListener(MouseEvent.CLICK, placeObject);
                        currentButton.addEventListener(MouseEvent.CLICK, placeObject);
              private function placeObject(e:MouseEvent):void
                   // if NavButton is clicked - make new visual targeted for moving in and currently visible object subject for moving out
                   if (e.currentTarget is NavButton) {
                        visualOut = visualIn;
                        visualIn = NavButton(e.currentTarget).targetObject;
                   else {
                        // otherwise - move visual out
                        visualOut = visualIn;
                   swapVisuals();
               * Accompishes visuals swapping
              private function swapVisuals():void {
                   if (visualIn) TweenLite.to(visualIn, .3, { x:0 } );
                   if (visualOut) TweenLite.to(visualOut, .3, { x:visualOut.hiddenPosition } );

  • Problem with eventListeners

    I have a slideshow in Flash/AS3 with frames having stop() commands, and goforward/goback buttons.
    I want to have some action on two of my frames. This is what I'm trying:
    myTimer = new Timer(40,0)
    myTimer.start()
    myTimer.addEventListener(TimerEvent.TIMER,update)
    where update (and update1) are functions with the scripts I need, one for each frame.
    It works fine, but the problem arises once you go to the second frame and then back to the first frame, the action becomes much slower and jagged. I believe this is because both eventListeners are active at the same time. How should I remedy this? Where should I place myTimer.removeEventListener?

    I've created a presentation flash. It has three frames and two layers. There are two buttons named forward and back on layer 1. I use the first frame simply as initialization with the following code:
    forward.addEventListener(MouseEvent.CLICK, function(e:MouseEvent){nextFrame()})
    back.addEventListener(MouseEvent.CLICK, function(e:MouseEvent){prevFrame()})
    I have two movieclips, say mClip1 and mClip, placed on frame 2 and frame 3 respectively on layer 2. Each of these has some moving stuff inside them as I mentioned above and I do this using myTimer1 inside mClip 1 and myTimer2 inside mClip2. The problem arises when the user clicks on the forward and back button to shuttle between frame 2 and 3, and new eventListeners and/or timers are being created each time, slowing the action tremendously. I can't place the removeEventListener for mClip1 anywhere in frame2 because that would stop the action. I've tried placing it in frame3 but I get errors: apparently I can't access mClip1 when I'm in frame3. Similarly if I create the timers in frame1, I can't access them in the other frames. For example, I tried on frame 1:
    timer1 = new Timer(40,0)
    then inside mClip1 in frame 2:   parent.timer1.addEventListener(...)     and I get AS3 complaining that it doesn't know about timer1 (Error 1010 A term is undefined and has no properties)
    If I write in frame 1:  timer1.addEventListener(TimerEvent.TIMER, mClip1.update)   then AS3 complains that it doesn't know about mClip1.

Maybe you are looking for

  • How can I transfer mp3 files from my PC to my Ipod Touch 4?

    I have an Ipod Touch 4 that was given to me. I use it almost exclusively to listen to audio books downloaded from various libraries. Once upon a time long ago I did manage to download some music (mp3 files) to the Ipod but I have no idea how. Now I w

  • Values are not reaching BAM Report

    Hi All, i have implemented a simple Bam adapter. The composite gives below fault while inserting data into BAM DataObject. <part name="detail"> <detail>BAM-06144: Cannot insert rows into data object /public/DataObject/HelloWorldDO.java.lang.StringInd

  • Photo downloads to Iphoto

    When I try to download photos from my iphone to my Mac I get an error message saying there is Insufficient Disk Space. I deleted over 100 photos and several movies but still get the message. Any help?.

  • "Save As" glitch, Illustrator CS4

    I've had a couple instances on Snow Leopard where Save As > AI.Illustrator CS4 generates a PDF instead. It's happened more than once though I don't expect I can reproduce the glitch reliably. I'm reminded of earlier versions in which clicking OK on a

  • Consumable Articles

    Dear all My clients wants to map the consumable artilces in SAP *Requirement  from tha client : client wants to procure consumable articles , for which Stock and value should update at Warehouse level and not at Plant level. THEY WILL RAISE PO only a