'Basic' external actionscript file/class usage

Hey All,
I'm a bit baffled by something that should, in my humble opinion, be a piece of cake...
The setup is really easy. A simple application with a single textinput, a button and a text component.
When the button is clicked a function is called that sets the text from the inputfield to the text component.
code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
            public function click(inputText:String):void {
                outPutTxt.text = inputText;
        ]]>
    </mx:Script>
    <mx:TextInput x="10" y="10" id="inputTxt"/>
    <mx:Button x="178" y="10" label="Button" id="Btn" click="{click(inputTxt.text)}"/>
    <mx:Text x="251" y="12" text="Text" id="outPutTxt"/>
</mx:Application>
As I said, really easy.
What I want to do is put the function 'click' into an external actionscript file or class. And still be able to, from within the external file, modify the outPutTxt stuff.
I'm aware that I could create a public bindable variable inside of the external file and then bind the outPutTxt to that variable, but I would really like to be able to 'simply' force the value...
Is that possible? If yes: how plix
If it's not possible, I'd like to know as well! And in that case, how would I then re-use the same instance of a class/file in multiple seperate components? Say I got a 'login' thingie where a user logs in (data stored externally in a seperate actionscript file/class) and I want to re-use that information on other pages... Or is this done automatically?
Any and all comments/answers are higly appreciated!
Pieter

Hey Levancho,
thanks for your answer!! Much appreciated.
However, the code you proposed threw an error...
Errormessage:
ReferenceError: Error #1069: Property outPutTxt not found on controls.Control and there is no default value.
    at controls::Control/btnClick()[C:\...\FlexTest_03\src\controls\Control.as:13]
    at FlexTest_03/__Btn_click()[C:\...\FlexTest_03\src\FlexTest_03.mxml:11]
So I tried something else where I bind the text in my OutPutTxt to a variable inside of the external class file.
Code:
Class:
package controls
    public class Control
        [Bindable]
        public var outPutText:String = "";
        public function Control()
        public function btnClick(inputText:String):void {
            this.outPutText =  inputText;
Mxml:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
            import controls.Control;
            [Bindable]
            private var control:Control = new Control();
        ]]>
    </mx:Script>
    <mx:TextInput x="10" y="10" id="inputTxt"/>
    <mx:Button x="178" y="10" label="Button" id="Btn" click="{control.btnClick(inputTxt.text)}"/>
    <mx:Text x="251" y="12" id="outPutTxt" text="{control.outPutText}"/>
</mx:Application>
And this basically did what I wanted to do... so I just need to do some major binding between my application and the classes I'll be using for my business logic.
Now for something else entirely...
Is there a way for me to pass the instance of my class between flex components?
Pieter

Similar Messages

  • External actionscript file

    Hi, I've more than two components accessing the same
    function. Hence, I would like the function to be on an external
    actionscript file.
    My codes are as followed:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:HDividedBox xmlns:mx="
    http://www.adobe.com/2006/mxml"
    width="100%" height="100%">
    <mx:Metadata>
    [Event(name="scaleChange",
    type="actionscripts.sliderChange")]
    </mx:Metadata>
    <mx:Script>
    <![CDATA[
    import actionscripts.sliderChange;
    import mx.managers.DragManager;
    import mx.core.DragSource;
    import mx.events.DragEvent;
    import flash.events.MouseEvent;
    import mx.containers.Box;
    [Bindable]
    [Embed(source="/images/map.jpg")]
    public var map:Class;
    public var oWidth:Number = 2800; //original map width - 1200
    public var oHeight:Number = 2100; //original map height -
    900
    public var xOff:Number;
    public var yOff:Number;
    private function dragMap(event:Event):void{
    event.currentTarget.addEventListener(MouseEvent.MOUSE_DOWN,
    mouseMoveHandler);
    private function doDragEnter(event:DragEvent):void{
    DragManager.acceptDragDrop(Box(event.target));
    private function mouseMoveHandler(event:MouseEvent):void{
    event.currentTarget.useHandCursor=true;
    var dragInitiator:Image=Image(event.currentTarget);
    var ds:DragSource = new DragSource();
    ds.addData(event.currentTarget, 'img');
    var imageProxy:Image = new Image();
    imageProxy.source = map;
    xOff = event.currentTarget.mouseX;
    yOff = event.currentTarget.mouseY;
    DragManager.doDrag(dragInitiator, ds, event, imageProxy, 0,
    0, 0.00);
    private function doDragDrop(event:DragEvent):void{
    targetMap.x = event.currentTarget.mouseX - xOff;
    targetMap.y = event.currentTarget.mouseY - yOff;
    public function onSliderChange():void{
    var temp:Number = 100-scale.value;
    targetMap.width = temp/100*oWidth+1200;
    targetMap.height = temp/100*oHeight+900;
    map.smoothing = true;
    var nWidth:Number = targetMap.width;
    var nHeight:Number = targetMap.height;
    var sliderObj:sliderChange = new sliderChange(nWidth as
    Number,nHeight as Number,"scaleChange");
    dispatchEvent(sliderObj);
    ]]>
    </mx:Script>
    <mx:Canvas id="scaling" width="75%" height="100%">
    <mx:VBox width="100%" height="100%"
    horizontalAlign="center" verticalAlign="middle">
    <mx:Box id="mapContainer" width="500" height="500"
    horizontalAlign="center" verticalAlign="middle"
    horizontalScrollPolicy="off" verticalScrollPolicy="off"
    dragEnter="doDragEnter(event);" dragDrop="doDragDrop(event);">
    <mx:Image source="{map}" id="targetMap"
    scaleContent="true" creationComplete="dragMap(event);" />
    </mx:Box>
    <mx:HSlider id="scale" liveDragging="true" minimum="1"
    maximum="100" labels="['1','100']" width="500" height="30"
    change="onSliderChange()" />
    <mx:Text text="{scale.value.toFixed(2)} km" />
    </mx:VBox>
    </mx:Canvas>
    <mx:Canvas width="25%" height="100%"
    styleName="sideBar">
    <mx:Label text="test test" />
    </mx:Canvas>
    </mx:HDividedBox>
    How do I make the drag and drop functions in the
    <mx:Script></mx:Script> to be in an external
    actionscript file so that this component can access it for the drag
    and drop to work?
    Any help is very much appreciated. ^^

    You can reference a external actionscript file in a
    <mx:Script source="myScripts.as"/>
    I do not use it this way as it is not a vary OO way to do
    things.
    I will generally create a singleton class (so it is only
    instantiated once)
    and use it for utility type functions.
    For example:
    public class UtilityClass
    private static var _instance:UtilityClass;
    public function UtilityClass()
    public static function getInstance():UtilityClass
    if(_instance == null)
    _instance = new UtilityClass();
    return _instance;
    public function myFunction():void
    Then in a mxml
    <mx:list id="list"
    dragDrop="UtilityClass.getInstance().myfunction()"

  • External Actionscript File not being Included

    Odd problem:
    Myself and a colleague are working on a project. We're both
    using Flash 8. We've both downloaded the latest Flash player.
    The project involves a series of perfume bottles, all lined
    up in a row. When you press a key on the keyboard, the associate
    bottle enlarges and some info on it appears. At the same time the
    other bottles fade out (an alpha change).
    The alpha change is driven using an external actionscript
    file, which is called (#include) at the top of the first line of
    script in the ‘main’ movie.
    The problem is, when I publish the swf file, the alpha change
    doesn’t work. When my colleague publishes it, it works. Why
    is this? It’s almost as if in publishing from my computer,
    the external .AS file is being ignored.
    I’ve tried calling the .AS file using a full path to
    the file. No change.
    I’ve tried uninstalling and reinstalling the Flash
    player, and older version of the player. No change.
    Here’s something else that’s odd: I’ve
    tried copying all the script from the external .AS file and
    embedding it into the main movie. No change. Is it that the
    publishing from my computer is corrupted? Other things I’ve
    published recently have worked fine?
    Any ideas?

    Yes, I've opened the AS file, and it seems ok. I've also had
    it sent to me a couple of times in case it got corrupted in
    transit.
    I've also tried copying the script from the AS file and
    embedding it into the 'main' movie at the #include statement (and
    removing the #include statement) so it doesn't have to look for the
    AS file, but this hasn't helped.
    I'll try making a different AS file with the trace statement
    you suggested, but I have other movies that call external AS
    statements, and they work.
    We're both running XP Pro w/ SP2.

  • How to import classes from an external actionscript file

    This is driving me crazy, I've been trying to resolve this on my own for ages, and I've reviewed a lot of different materials, but I still can't seem to just import some external actionscript classes correctly.
    I'm using Flash Builder 4 with the Flex 4 SDK on mac osx 10.6
    the class I'm trying to import (I'll call it DesiredClass) is in a folder like this
    /libraries/com/foreignproject/com/foreignproject/DesiredClass.as
    within the class itself, the package declaration looks like this (I left all the guts out for clarity):
    package com.foreignproject
        import flash.display.Sprite;
        public class DesiredClass extends Sprite
            public function DesiredClass()
    I'm working on a totally different actionscript file at
    /Users/username/Documents/Adobe Flash Builder 4/TestProject/src/TestProject.as
    in this file I try to import the DesiredClass:
    package
         import com.foreignproject.DesiredClass;
         import flash.display.Sprite;
         public class TestProject extends Sprite
              public function TestProject()
              var neatClass:DesiredClass = new DesiredClass();
    And then I try to add the class I want to the source path.
    I've tried adding each folder to the source path separately:
    /libraries/com/foreignproject/com/foreignproject/DesiredClass.as
    /libraries/com/foreignproject/com/foreignproject/DesiredClass.as
    /libraries/com/foreignproject/com/foreignproject/DesiredClass.as
    /libraries/com/foreignproject/com/foreignproject/DesiredClass.as
    /libraries/com/foreignproject/com/foreignproject/DesiredClass.as
    If I choose the libraries folder or either of the com folders then an error shows up in theTestProject.as file, saying:
    Definition com.foreignproject:DesiredClass could not be found.
    But f I choose either of the foreignproject folders then an error shows up in theDesiredClass.as file saying:
    a file found in a source-path must have the same package structure 'com.foreignproject', as the definition's package, ".
    What am I doing wrong? Please help. I bought a book on actionscript, started doing the flex-in-a-week series, read numerous online discussion boards, and I still can't import these classes.
    Thanks in advance.

    I don't know if this method is supported anymore but you can give it a try.
    If you backed up bookmarks in IE using the following directions, you should be good!
    *In IE, "File -> Import and Export -> Export Cookies".
    *Open newly exported "cookies.txt" in a text editor and put a period before every line that starts with a domain. So a line starting with <b>altavista.com TRUE / FALSE 1388491200 AV_ALL 1</b> will become <b>.altavista.com TRUE / FALSE 1388491200 AV_ALL 1</b>
    *Then, move the "cookies.txt" file to your profile folder.
    You can get to the Profile folder two ways
    *Help > Troubleshooting Information > Profile Directory > Show Folder
    or
    *Go to '''about:support''' and click Show Folder next to Profile Directory.

  • Flex 3 vs Flex 4 Preprocessor directives and code behind (External Actionscript file)

    I have a framework that I've built that I want to use on Flex3 and Flex4.
    I've added pre-processor directives as per this link (http://livedocs.adobe.com/flex/3/html/help.html?content=compilers_21.html) and got my Flex 4 code to compile nicely.
    I then went to flex 3 and discovered my sub-class of Application wouldn't compile because it was based off of spark. No problem, I'll add in a directive.
    Except now my overridden class has duplicate code, specific to which SDK it is using.
    No problem, I'll put all of the application class code in an Actionscript file and include it in both Application class declarations for each directive.
    It works nicely in Flex 3, so I went to Flex 4, tried to compile and now I'm getting compiler errors saying things such as "The (private|public|protected) attribute may only be used on class property definitions." and "The (private|public|protected) attribute can only be used inside a package.
    This same file works in Flex 3, but not in Flex 4.
    What can I do to make the code compile in both places?
    I'll work on a simple case so I can upload some code.

    Nevermind.
    I got around this issue by renaming my sub-classed Application to "...Application".
    Now I can use a directive to specify an import statement for the extends Application portion rather than specifiing the fully qualified spark.components.Application or mx.core.Application.
    Lame - but done.

  • JavaScript alert in AS3 or AS2 to debug the external actionscript file

    Hi,
    Is there any way to debug the external AS file as i dont want to use "trace".
    I have an idea to use the input text field the check the variable/function is working right but this is not enough so is there any process in AS2 or AS3.
    Thanks in advance..

    my mistake ..i have used there dynamic textfiled.
    but i got a easy solution by using
    getURL ("javascript:alert('Testing');");
    but this is not the good solution
    is there any way to import the alert contolls in AS2
    like i have read somewhere
    import mx.controls.Alert;
    Please reply..

  • How to pass data from external Actionscript file to MXML file

    HI...
    I do not know about the Application.application.whateverFieldIWantToReference and it does work on my computer, but only when the external .as file is in the same folder as the main .mxml application... But in my case, the .as file is in another folder (ie. package)...
    Also i want to know When I use the standard Application.application way, it does not spit out any error, but it just doesn't work either.
    Alternatively, I guess I could pass the field (in this case, a  TextArea) as an argument, but how do I do that? How to pass a  TextArea(or any other element, for that matter) as an argument? What  type is it?
    Does anybody know how to circumvent this? Any help is appreciated,
    Thanks.

    HI...
    I do not know about the Application.application.whateverFieldIWantToReference and it does work on my computer, but only when the external .as file is in the same folder as the main .mxml application... But in my case, the .as file is in another folder (ie. package)...
    Also i want to know When I use the standard Application.application way, it does not spit out any error, but it just doesn't work either.
    Alternatively, I guess I could pass the field (in this case, a  TextArea) as an argument, but how do I do that? How to pass a  TextArea(or any other element, for that matter) as an argument? What  type is it?
    Does anybody know how to circumvent this? Any help is appreciated,
    Thanks.

  • Calling a function in an external actionscript

    Hi. First of all I'd like to put my hands up and say that what I know about Flash is antiquated (I used to work with Flash 4 / 5), and have now been thrown into the deep end, as it were.
    I have an application that has a button component. In an external actionscript file there's an event listener that calls a function when this button is pressed. I want to replace the button with a graphic that switches according to whether the button is 'on' or 'off'. I've created a movie clip that cycles back and forth between the on and off states when clicked, but the trouble I'm having is getting it to call the function. I have no idea how to do it, other than to just include function_name(); (or call.function_name();) in the onRelease handler (which doesn't work). Is it possible to use event listners for movie clips (rather than components?) Or else how can I call this function? It should be really simple and I'm tearing my hair out trying to get it to work! The function is declared 'public', by the way...
    Oh yes, this is ActionScript 1 (I think...)
    Eternal thanks and gratitude to anyone who can help me...

    Do you mean to copy it here, or copy it into the fla? I've already tried doing the latter, which doesn't work - the script imports other external as files and I think that that's messing things up. The function only seems to work when it's located in this external file. The function I'm trying to call is
    public function toggleAudio() {
           //if (btnAudio.label == "Sound Off") {
           if (_root.audio == "mute" or btnAudio2.label == "Sound Off") {
               trace("toggleAudio AUDIO: Off");
               //btnAudio.label = "Sound On";
               _root.audio = "unmute";
                         // stop recieving audio from in stream
               ServiceLocator.getInstance().getService("nsService").returnInStream().receiveAudio(false) ;
               // stop sending audio on out stream
               ServiceLocator.getInstance().getService("nsService").returnOutStream().attachAudio(null);
                     } else {
               trace("toggleAudio AUDIO: On");
               btnAudio2.label = "Sound Off";
               _root.audio = "mute";
                         // start recieving audio from in stream
               ServiceLocator.getInstance().getService("nsService").returnInStream().receiveAudio(true);
               // start sending audio on out stream
               ServiceLocator.getInstance().getService("nsService").returnOutStream().attachAudio(Servic eLocator.getInstance().getService("camService").returnMic());
    The bit at the beginning where I've commented some stuff out is where I've been trying out different things to get it to work.
    For all intents and purposes though the function could be
    public function please_work() {
    trace("I work!");
    All I need is for a way to call this from the main flash movie

  • Why do button functions included in external actionscript not persist across frames?

    this one drives me nuts!
    if i include an external actionscript file in frame one of my
    movie, then [as you'd expect] all the functions, global variables
    etc contained in that external AS file are available throughout my
    movie - with one notable exception.
    if i add a button to the stage - in a frame other than frame
    one - whose onRelease handler is defined in the external AS, the
    function is not called when the button is clicked - i have to
    re-include the external AS file again on the frame in which the
    button resides, in order for the buttons function to be called.
    anyone know why this is - and if there's a way round it?
    how come all the other functions in the AS persist across all
    frames and all timelines in the movie, but the button handlers only
    seem to be available on the actual frame in which the AS file is
    included?
    download
    example

    I think you and I are dealing with similar issues and the
    root cause is referred to as "scope." The only difference between
    your and my problems is that your code is in an external as file
    and mine is on the timline. But in both instances, code that should
    work doesn't. Robert Reinhardt has covered this in an article at
    http://www.communitymx.com/content/article.cfm?cid=8E4DF.
    He is the author of the Flash Actionscript Bible series and so
    knows what he is talking about. I have been studying it for an hour
    and darn if I can understand the second page of it. I've asked for
    help myself about this at
    http://www.kirupa.com/forum/showthread.php?t=248316.

  • Loading external as file through url

    Hi
    I have external actionscript files that I call like this:
    #include "../events/allevents.as"
    But if I want to inport the full URL i.e.
    #include "http://www.essentialeventsmanagement.com/events/allevents.as" it does locate the file although it is the correct URL. How can I set this up so it always calls the server as and not my local as file
    Thanks
    Mark

    Ok thanks for clearing that up... is there a way to load this file dynamically?
    Thanks
    Mark

  • Classes may only be defined in external ActionScript 2.0 class scripts.

    i try to use the BitmapExporter 2.2.
    i inserted the .as file into the first frame in my fla but
    when i try to test movie i get
    "Classes may only be defined in external ActionScript 2.0
    class scripts."
    since i am not expert in extensions - what did i do wrong and
    hoe can i properly use this extension?

    remove the .as file code from your fla. put the .as file in
    the same directory with your flash files. when you publish your
    swf, flash will incorporate the .as code in your swf when you use
    the new BitmapExporter() statement.

  • Flex Gumbo - Library Path "Include all classes" includes ActionScript Files

    I've added an "Actionscript File", i.e. a File with no package/class that is included in an actionscript class.
    In FlexBuilder 3, since there was no option to include all classes, I could optionally choose actionscript files.
    So, Make Flashbuilder's "include all classes" option to not include Actionscript Files by default.

    I opened a bug on jira.
    http://bugs.adobe.com/jira/browse/FB-22228

  • Unloading external swf file keeps memory usage growing up

    Hello everybody,
    The idea is very simple: I have a submain.swf with 5 buttons. Each button loads an external .swf file.
    com_loader.load(URLRequest);
    After playing first external swf, before I go to next one, I try to unload it:
    1. remove all its associated listeners:
    com_loader.contentLoaderInfo.removeEventListener(Event.INIT-PROGRESS-COMPLETE, idFunction);
    2. unload it:
    com_loader.unload();
    3. set to null:
    com_loader = null;
    and load next external swf file and so on.
    The problem is that the FireFox/IE8.0 Memory Usage in Task Manager is going up and I see no sign of GC activity even after 5 mins of playing. Can anyone light me up pls? This is the second week working around and no good news until now.
    Thanks in advance.
    P.S.
    If I try com_loader.unloadAndStop(); it gives me the error: Error #2044: Unhandled IOErrorEvent:. text=Error #2036: Load Never Completed.
    Vince.

    Hi Ice,
    The loaded swf file contains only a small photo, just for testing, with no listeners or other stuff in it.
    Vic.

  • Calling actionscript file package classes

    I have composed a simple actionscript class called "test.as"
    under this directory \project\as\test\.
    The test.as class is packaged as "package as.test".
    In my main flex file main.mxml, how can reference this
    test.as class without getting a complied error by not packaging up
    the package as "package project.as.test"? Any approaches to this
    problem? I know in java it can be done with Jar package.

    quote:
    Originally posted by:
    MR Fang
    Sorry if I didn't communicate clear on my original question.
    Let me reintegrate my question on the actionscript package.
    If I created an actionscript file and main.mxml under these
    directory,
    \project\as\utils\features\test.as
    \project\main.mxml
    and in the test.as, I packaged the file as strictly below
    package utils.features
    { public class Test.{...blab...blab...}}
    Is it possible to reference the "test.as" class without
    explicitly using package directory as
    package as.utils.features?
    Will this create a problem when I call this class from the
    "main.mxml"? How do I manage to compile and use this type of
    package structure?
    Thanks,
    Fang
    in your MXML you would say...
    <mx:Script>
    <CDATA....
    import project.as.utils.features.test;
    private var myClassInstance:test = new test();
    ]]>
    </mx:Script>
    or... if test.as extended something like a <mx:Button/>
    you can do something like this..
    In your MXML, in the Application tag add...
    <mx:Application ...
    xmlns:myCustomNS="project.as.utils.features.*" >
    <myCustomNS:test />
    </mx:Application>

  • Exit Android App with external *actionscript.as* files

    Hi, i'm trying to make this code work with a application that got 99% of code driving by external actionscript.as files;
    In another app without any external call i mean no actionscript.as files, the code work very fine.
    My goal is to shutdown any activity of the app when the user receive a call or something like that;
    Many thanks in advance and sorry my english
    Scene 1, Layer 'Layer 1', Frame 1, Line 14
    1046: Type was not found or was not a compile-time constant: KeyboardEvent.
    function handleActivate(event:Event):void
        NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.KEEP_AWAKE;
    function handleDeactivate(event:Event):void
        NativeApplication.nativeApplication.exit();
    function handleKeys(event:KeyboardEvent):void        ----- Line 14 -----
        if (event.keyCode == Keyboard.BACK)
            NativeApplication.nativeApplication.exit();
    if (Capabilities.cpuArchitecture == "ARM")
        NativeApplication.nativeApplication.addEventListener(Event.ACTIVATE, handleActivate, false, 0, true);
        NativeApplication.nativeApplication.addEventListener(Event.DEACTIVATE, handleDeactivate, false, 0, true);
        NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, handleKeys, false, 0, true);

    Look Mr. Colin, added the import flash.events.KeyboardEvent; and thats what i got:
    Scene 1, Layer 'Layer 1', Frame 1,
    Access of undefined property:
    NativeApplication
    SystemIdleMode
    Keyboard
    Capabilities
    I'm addind this code inside Flash CS6, not via external.as

Maybe you are looking for