Is it possible to pass an argument to the function triggered by an event handler?

Hi all
Try to migrate my way of thinking in AS2 to AS3/CS4.
OK, I have 2 buttons on the stage. Each button almost did the same thing, so I want to create a unique function, and each button calls this function even (we'll name this function 'Navigate')... However, the function will have to end up doing something different dependent on which button was clicked.
If, previously, in AS2, I would have added the code on the buttons themselves with methods we (release) (see the SAMPLE CODE 1)

Thus, each button calls the function efficiently navigate and transmits a different image to the function tag.
Now, I try to recreate this feature in AS3. As you know, it (release) has been abolished (still do not know why), but we must now use event handlers, so I'll try to find a way to pass a different image to the function label argument to navigate. Currently, I can achieve that by using a switch statement to test which button has been clicked and act accordingly (see the SAMPLE CODE 2).

In this simplistic example, this works very well, but in the real world, I have more than 2 buttons and the function navigate would probably much more complicated...
So I would be able to pass an argument (as in the AS2 example) to the function to navigate... maybe in the addEventListener() method? I tried, but got compile errors (see the EXAMPLE CODE 3):

The issue of the $ 1 Million:
Is it possible to pass/change dynamically an argument to a function that is triggered by an event listener? (Or is the event that triggered the function the only argument you have?)
If this is not possible, I would like to hear how you people it would handle (other than to have a switch with 12 cases in there)?

I found a few solutions that I'll post below for prosperity...

You can create a dictionary indexed by the targets of future events and store information in there you want to associate with them. Then the Navigate function check that the dictionary to get its parameters:

Code.
Button1.addEventListener (MouseEvent.CLICK, navigate, false, 0, true);
Button2.addEventListener (MouseEvent.CLICK, navigate, false, 0, true);

var buttonArgs:Dictionary = new Dictionary();
buttonArgs [Button1] = "FrameLabel1";
buttonArgs [Button2] = "FrameLabel2";

function Navigate(e:MouseEvent):void {}
gotoAndStop (buttonArgs [e.target]);
}

This to me, is about the same amount of work than writing a long, but a bit more elegant switch statement, I guess.

I had a little trouble understanding the following solution, because I did not quite understand important information about event listeners. The addEventListener () method requires a function as the 2nd argument passed to it.
It didn't quite click on until someone reminded me: Navigate is a function... Navigate("FrameLabel1") is a callfunction...

So by writing simply navigate, I'm not actually calling the function when calling the addEventListener method, I'm just providing the event with a reference the name listener. Then, when the listener is triggered, the listener will call (and pass a MouseEvent argument to) navigate the function.

Conversely, by writing Navigate("FrameLabel1") as 2nd argument, the event listener trys to run the function navigate both the addEventListener method is instantiated. And, since then, in this example, the function navigate returned as ": Sub" a compilation error would occur because as I said, an event listener requires a function as 2nd argument data type. This would be essentially as written addEventListener (MouseEvent.Click, Sub, false, 0, true)
However, there is a way to get around this... basically, instead of setting the function navigate as returning an empty data type, you define a function to return data type and then nest another function (which actually contains the actions you want to run) on the inside.

Button1.addEventListener (MouseEvent.CLICK, Navigate ("FrameLabel1"), false, 0, true);
Button2.addEventListener (MouseEvent.CLICK, Navigate ("FrameLabel2"), false, 0, true);

function Navigate(myLabel:String):Function {}
return function(evt:MouseEvent):void {}
gotoAndStop (myLabel);
}
}

Tags: Adobe Animate

Similar Questions

  • How can I build and pass a variable to the function getField?

    I need to know how to build and pass a variable to the function getField():

    I have a form of several sections similar to a spreadsheet.  Each section contains 5 rows of 11 columns.  Currently I have calculations in the field I want to consolidate and move to the level of the document.  The field names in each column are identical except for a row identifier.  For example, in the 1st row: a_debtType1, a_debtTerm1, adebtRate1, etc.  I want to be able to pass to a function of level document line identifier and that connect a function "getField.  Here is an example:

    Document-level:

    function calculateLoan (lineNumber) {}

    var myDate = getField("a_debtType"+lineNumber).valueAsString;

    var myDate = getField("a_debtTerm"+lineNumber).valueAsString;

    .. few treatment

    return

    }

    Level of the form:

    change the information in the form is ready for line 1

    function calculateLoan("1");

    Thanks in advance for any help.

    It seems good except how you call the function of what you have. The calculation script should be something like:

    Custom calculate script

    calculateLoan("1");

    Note that you can also get the line number if it is contained in behalf of the field that calls the script if you don't disturb him passing as parameter, assuming you named the fields correctly.

    For example, to calculate the field is called "row_total.1", you can get the line number in the script like this:

    var no_lig = event.target.name.split(".") [1] ;

  • Passing of Arguments to the Bean with EL method

    Hello:

    11.1.2.3 Jdev

    I created the following managed Bean (see below) in a taskflow with scope of Backing Bean. I can call fieldColor ok with
    EL as in #{backingBeanScope.CheckTimezone.fieldColor}-> works ok

    But now I want to pass a string value to the testDate method and returns a string. What is the El to make this work?
    I tried:

    #{backingBeanScope.CheckTimezone.testDate ('someString')} but it does not work and said testDate is not recognized.

    What is the correct way to call this method by passing a string arg?

    Are there articles that explain this?

    Thank you very much...





    public class CheckTimezone {}
    private String fieldColor = "in late';

    public CheckTimezone() {}
    Super();
    }

    {} public void setFieldColor (String fieldColor)
    this.fieldColor = fieldColor;
    }

    public String getFieldColor() {}
    System.out.println ("called getFieldColor");
    Return fieldColor;
    }

    public String testDate (String subsist) {}
    System.out.println ("called testDate, passed in value is:" + stand);
    Return fieldColor;
    }


    }

    In case, you can create a property testDate in your bean that returns a map object.

    public class CheckTimezone {}
    private String fieldColor = "in late';
    Private final FunctionMap functionMap = new FunctionMap();

    public CheckTimezone() {}
    Super();
    }

    public String getTestDate (String subsist) {}
    Return functionMap;
    }

    Internal class implementation of the map
    Public NotInheritable class final FunctionMap implements {map
    private FunctionMap () {}
    Super();
    }
    public int size() {}
    return 0;
    }
    {} public boolean isEmpty()
    Returns false;
    }
    {} public boolean containsKey (Object key)
    Returns true;
    }
    public boolean containsValue (Object value) {}
    Returns true;
    }

    Write your logic here
    public Object get (Object date) {}
    System.out.println (date);
    }

    public Object put (Object key, Object value) {}
    Returns a null value.
    }
    public Object remove (Object key) {}
    Returns a null value.
    }
    {} public void putAll (map m)
    }
    Public Sub clear() {}
    }
    {} public Set keySet()
    Return Collections.emptySet ();
    }
    public Collection values() {}
    Return Collections.emptySet ();
    }
    {} public entrySet() Set
    Return Collections.emptySet ();
    }
    }

    }

    In your page jspx - #{backingBeanScope.CheckTimezone.testDate ['someString']}

  • arguments of a function

    Hi there.
    is a way to get the arguments for the function onFinishTween? (for event onComlete)
    TweenLite.to(MC, 1.5, {alpha:1, tint:color[Math.floor(Math.random()*(color.length))],onComplete:onFinishTween});
              function onFinishTween():void {
                             //trace("The tween has finished! b-) ");
                             //reNew();
                        }
    

    I want to cheack all finieshfunction;
    Thank you very much

    You are welcome.

    p.s. If you're still able, please mark this thread as answered.

  • Passing multiple arguments to a CFC

    Currently, I connect to Coldfusion with a RemoteObject and pass a single argument. Is it possible to pass multiple arguments? Just add a comma separated by the argument list in the parens competence does not seem to work.

    "" < mx:Application xmlns:mx = ' http://www.adobe.com/2006/mxml ' layout = "absolute" creationComplete = "initApp (event)" >

    -Block of Script.

    private void initApp(e:Event):void {}
    chartmth_RO.qMonthlyUsage (200804);
    }
    ----
    < mx:RemoteObject id = "chartmth_RO" showBusyCursor = "true" destination = "ColdFusion" source = "usagecenter_local.cfc.charts_usage_mth" >
    < name mx:method = "qMonthlyUsage" result = "get_Result (event)" / >
    < / mx:RemoteObject >

    Once more I am kicking. You can pass multiple arguments in a CFC using a comma separate list the key is to encapsulate each string between apostrophes. So let's say I want to pass the arguments saleschart, fiscal year 2008, 300. The inside of my call parens jurisdiction would look like ('saleschart', 'exercice2008', 300).

    I love it when an answer is revealed, but I hate when it seems so simple.

  • Chr (44) to replace the commas separating the arguments of a function?

    In Oracle SQL, it is possible to replace the commas between the arguments of the function with chr (44)?  A simple example with substr():

    substr ("yyyy", 1, 1) - the result is 'a '.

    vs

    substr ("aaaa" chr (44) 1 chr (44) 1)-this should also return 'a '.

    Is there a way to make the second example works the same way as the first?  I tried different techniques escaping, string concat, etc., and I failed.  Is there a method to replace the comma (",") the character of the way I'm looking for or is this impossible?

    Thank you

    N °

    The Analyzer seeks commas, not for other things you as a human being assimilated by a comma.

  • Passage of the Arguments to the Planner channels

    Comrades of the Oracle,

    can I pass arguments to programs in a string?

    What works already call a program a job, passing an argument to the program. So far so good.
    What I am to do is run a chain of Planner, where one of its steps starting this program.

    Now, when I create a line work, I can not add an argument value more with

    DBMS_SCHEDULER. SET_JOB_ARGUMENT_VALUE

    because this will raise an ora-27475.
    Looking at the docs that it seems as if there is no way to do what I want - which I thought I could take for granted...
    Any ideas, anyone?

    I'm on 11.2.0.2.
    Kind regards
    Uwe

    "There is no direct way to pass parameters to a stage of the chain on the fly, but there is a way to bypass it." More details-> Re: pass parameters to a program

  • By passing a string as the name of a function of mouse event listener?

    Hello

    I am trying to essentially pass a string as a function name in an event listener, but I do not know how to approach the issue.  Is there a way to convert a string to a function?  I don't know how to Word my question, so I apologize.

    Here's some code I have for me to show you what I'm doing.

    package {}

    some import declarations

    public class changes extends MovieClip {}

    var functionName:String
    var aBox: Sprite;

    public void changes() {}

    nomfonction = "hemagg";

    createButtonBox (16, 16, 32, 32, functionName);

    }

    public void createButtonBox (anX:Number, aY: number, aWidth:Number, aHeight:Number, aFunction:String) {}


    aBox = new Sprite();
    Some code for box drawing

    aBox.addEventListener (MouseEvent.CLICK, [aFunction] ())?

    addChild (aBox)

    }

    public void aFunction(event:MouseEvent) {}

    trace ("test");

    }

    }

    }

    I'm on the right track, or is not possible?

    Anyway, thanks in advance.

    If you pass a string representing a function name, then you must use the notation of support to have this interpreted as an object/function string.  Try to use...

    aButton.addEventListener (MouseEvent.CLICK, this [functionToCallTo]);

  • passing parameters to functions triggered event

    Hi all
    I created a button and added EventListener.
    as mybutton.addEventListener (MouseEvent.CLICK, clickSt);
    When I apply the clickStart function (event: MouseEvent) I'd like to
    an array, a string to the function as parameters. How can I do this.
    is it possible or not.
    thanx.

    Well, not this way.
    The function automatically receives a parameter when you create a reminder with this 'addEventListener' function, this parameter is datatyped as the event type that you defined in the callback, in your case "MouseEvent". If you want to pass more data when the function is called so you have create your own event class because almost all of the events just inform when something happened and send limited information. You can consult the documentation on creating a custom event class, there is a lot of info on the subject.

  • Pass values to the function vs object pass to the function

    What is the best way to pass some values to the function?

    It is sufficient to indicate the characters or arrays of char etc something like this: function (float x, float [] z)

    or

    Create class (object)... say ValuesToPass vltp;  with the variables, the set and get methods.

    Assign values: vltp.setX = blah, blah = vltp.setZ

    ...  And not vltp to the function like this: function (vltp) and the values of the extract by using the get methods...

    What sense would be less time and consume of heap space?

    From my point of view - by passing the values as values would be faster, but I'm new to java and can't be 100% sure on this subject...

    Thank you

    If a method will work on three different bits of data, such as arrays of 2 char and int, so I suspect that most people would say just pass these as parameters rather than creating a "temporary" object just to contain these.

  • How to pass parameter in the function using the select statement?

    Hello

    I had a problem. I can't pass as parameter to the function by using the select statement. But it can pass as a parameter using the "code". How can I solve this problem?

    For example,.
    Select * from table (SplitFunction ('HS750020, HS750021')) < < < this work.

    but

    Select * from table (SplitFunction (select LOT_NO in the TRACER_SEARCH_SCHEDULE where JOB_ID = '36')) < < < do not work.

    Thank you for trying to help him. Thank you.

    Select * from table (SplitFunction (select LOT_NO in the TRACER_SEARCH_SCHEDULE where JOB_ID = '36'))< do="" not="">

    Try like this

    select * from table(select splitfunction(lot_no) from tracer_search_schedule where job_id='36')
    

    Just make sure that your subquery returns only 1 row.

  • How to pass arguments to the SQL Script in command prompt

    I don't know about the ' & nom_de_variable "to request a value in the command line.

    But, how can I pass arguments from the command line for the following script to the command - prompt

    Example:

    ex_proc. SQL

    CREATE OR REPLACE PROCEDURE ex_proc (employee_id NUMBE IN)
    IS
    v_emp_id Number (38);
    BEGIN

    v_emp_id: = employe_id;

    UPDATE emp_employee SET sal = 2000 WHERE emp_id = v_emp_id;

    END;
    /


    call_ex_proc. SQL

    Appellant for procedure above:

    BEGIN

    ex_proc (100); -The employee id is 100.

    END;
    /

    Here are the General controls that we use to run the scripts above-

    SQL > @ex_proc.sql

    SQL > @call_ex_proc.sql



    But my requirement is to pass the employee id as an argument in the command line as.
    SQL > @call_ex_proc.sql 100

    Is it possible to pass command line arguments?

    Usually this question start with reading documentation, wouldn't it?

    Solomon Yakobson showed you the method gross and unreadable.

    You will use best

    set = '& 1' '.

    -use & in the rest of the code

    ----------
    Sybrand Bakker
    Senior Oracle DBA

  • Passing arguments to the script

    Hello

    I have created a dialog box load the files in the folder and when I click the button I run another script of command StartScript (...)

    How can I pass arguments to the script (the paths of files)?

    Thank you

    Hey OzShimon,

    As long as you use a tiara predefined global variables (T1, T2,...)  you'd be fine. You can also define user variables (.) SAV files) or even to declare your own global variables with: call GlobalDim ("Myname").

    These variables are not re-initialized until you restart the script engine. So just change 'obj' for T1 your test should work

    ' Dim obj

    Void Button1_EventClick (ByRef This)

    T1 = "Hello World".

    Call ScriptStart("C:\Users\Oz\Desktop\test.vbs")

    End Sub

    * the script code (test.vbs):

    Call MsgBox (T1)

    Kind regards

    Javier

  • Is it possible to pass variables in FledgeController?

    We have some environment variables that change instance of Simulator, and it would be better that we could transmit in the Simulator, rather than having to write them to a file in the application to read running. Is it possible to pass variables in the FledgeController so they can be used as the app system environment variables?

    I don't think it's possible to pass via a command line.  But you can store this value in a file on your hard disk, Simulator one card micro SD and read the file in your application (although you mentioned that you do not want to).

    If you install via a JAD file, you can add the parameter to your JAD file and access them from your application.  But it's probably more complicated than to write a file.

  • How to pass an argument of javascript to java extension

    Hello, I have an application running with a Java Extension.

    For the course of time, I only call some java extension methods (ScriptableFunction, but now, I have to pass the variable javascript (arguments) to the extension.

    I call a method with:

    // In: public final class MyCamera extends ScriptableFunction
    
    public Object getField(String name) {
    
        if (name.equals("getImage")) {
         return callGestorCamera.pushUICameraSnapshot();
        } 
    
        return new String("do nothing");
    }
    

    and javascript :

    function getImage() {
        var name = mycamera.camera.getImage;
        return name;
    }
    

    and run correctly.

    But now I have to pass one argument, as some URL, and I don't know how to do.

    I try to move the handful of Java class to Javascript, something like this:

    // In: public final class MyCamera extends ScriptableFunction
    
    public Object getField(String name) {
    
        if (name.equals("getImage")) {
         return callGestorCamera.pushUICameraSnapshot();
        } 
    
        if (name.equals("getObject")) {
         return callGestorCamera;
        }
    
        return new String("do nothing");
    }
    

    and javascript :

    function setUrl(url) {   var handle = mycamera.camera.getObject;        handle.setUrl(url);
    
        return true;}
    

    but is not running and try:

    mycamera.camera.getObject.setUrl(url);
    

    but does not work.

    What is the way?

    Thank you!

    I believe that the Extensions lab shows how to pass a parameter to a function... For example, he spends the duration of the vibration.

    http://NA.BlackBerry.com/eng/developers/devbetasoftware/Lab_Widget_Extension.zip

Maybe you are looking for

  • I think Firefox is getting worse, because there are many Web sites that does not work properly with it, while my other browser Google Chrome can.

    There are many sites, but I will say only 1 site because I have very bad memory, so here's the problem, Web site Furaffinity.net, search for his website may not work properly with Firefox, its advanced research, help and toggle the button description

  • NI 9205 analog incorrect values in multichannel mode

    Hello everyone I am actually measuring 10 battery cell voltages (which are connected in series) with a NI 9205 (slot 1) in a frame NOR cDAQ-9172. The voltage of each cell is measured in differential mode with channels 0 through 7, 16 and 17. I have n

  • (Redirected) Update CPU now black/green screen

    I had an Alienware x 51 R2 with an i5-4460 and upgraded to an i7 - 4790 k. However when I did it was a bit slow at the start, then he stopped on a black screen for a few minutes then went to a green screen as if I was able to sign again it was just a

  • ACS 5.1 - AD authentication LDAP VS

    Any help on this would be great I can manage to get my account record in the thinking of Active Directory configuring cisco switch in the external identity stores but not my setup LDAP here are a few successful newspapers, log in and unsuccessful new

  • LAPTOP BLACK SCREEN

    EVS SONY notebook PC series turns on, but no display so that the lights are on, rotating fan and it turns off automatically after one minute. What can be the reason? How to solve this problem? Hoe to reset a motherboard?