Using Flex 4, I have created an SWF that has the following code:
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import com.Index ;
protected function start(event:FlexEvent):void
{
this.addElement (new Index());
}
]]>
What I am trying to do is load the SWF into another SWF and access this class. The problem is the Flex class Main is what is recognized by the loading SWF. I have tried accessing its children(elements), but the added item is not there.
My ultimate goal is to load an SWF that has an object that can interact with the loading SWF.
lee
Addition:
Thanks for your addition. The code is working now, but it only access the Flex class created by the MXML. Here is the complete MXML:
<?xml version="1.0" encoding="utf-8"?>
width="1000"
height="700"
creationComplete="start(event)"
>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import Test;
protected function start(event:FlexEvent):void
{
this.addElement(new Test ());
}
]]>
To try and extract the class Test, I did the following:
var MainC:Class = L.contentLoaderInfo .applicationDomain .getDefinition ("Main.Test") as Class;
var O:Object = new MainC();
This returns 'Error #1065: Variable Test is not defined.'
I get the same result if I use ...getDefinition("Test").
If I use ....getDefinition("Main"), it works fine. But I cannot seem to reach into the class it creates to extract anything.
lee
The best way to go is to have that swf as a library (swc) and link it to your project. That way you could achieve strong typing, and access the underlying classes.
If you don't have access to neither the library release of the swf object, nor it's source to build the swc library yourserlf, you can still use the external classes, but not with strong typing:
var ExtIndex : Class = loader.contentLoaderInfo.applicationDomain.getDefintiion("Index");
var instance : Object = new ExtIndex();
this.addElement(instance);
so you must define your instance as Object.
Although, in case the Index class in your swf implements an interface that you know of (you have it in your project), like I_Index, you can use it instead of Object:
var instance : I_Index = new ExtIndex();
this.addElement(instance);
You might also find this article useful in deciding which way to go.
Update 1
Declaring the loader in Flex:
var loader: flash.display.Loader;
[...]
var ExtIndex: Class = loader.contentLoaderInfo.applicationDomain.
getDefinition("your.package.Index") as Class;
In case you have your Index class in a package (other than the default), you should specify it in its name. The code above searches for the Index class inside the your/package package.
API Docs for getDefinition:
Gets a public definition from the
specified application domain. The
definition can be that of a class, a
namespace, or a function.
Parameters:
name The name of the definition.
Returns: The object associated with the definition.
Throws: ReferenceError - No public definition exists with the specified name.
Language Version: 3.0
Player Version: Flash 9, AIR 1.0
Update 2
To make the Test class defined in your external application accessible from other flex applications by loading the swf that contains it, you must have a variable declared with that type inside your swf's main application. Otherwise that class won't be compiled into the swf (to save the size of it). Flex only compiles classes actually in use into the swf, so it's not enough to just import a class. In the main application of your swf you should declare:
var _tmp:Index;
This makes sure that the Index class will be compiled into your swf, and you can access it from an other application which loads that swf.
Update 3
You can check out how this works at this link. The source code is included too.
Since there are two projects, in the [src] folder you can see the test's source, and in the [source path src] folder the source of the externally loaded swf file.
If you download the whole project, make sure that you separate the two projects.
Related
I'm using Flash Builder 4.5. In an .mxml file, if you want to use an actionscript function residing in an external .as file, one simply adds to the .mxml file:
<fx:Script source="filename.as"/>
where filename.as contains the actionscript function(s).
Is there a way to do a similar thing from an .as project file? That is, I have an actionscript project created in Flash Builder 4.5 (e.g. no .mxml files anywhere), and I have a nested actionscript function. How can I place that nested actionscript function in an external file, then call it from the original file? My goal is to have that nested actionscript function be called from multiple other files, so I don't have to nest it multiple times.
The easiest way to do this is with a static function. Create an AS class file and remove the constructor. Now place your function in it and set the type to "public static", here is an example of a simple "stirng utility" class.
package some.place.inyourapp
{
public class StringUtils
{
public static function contains( string:String, searchStr:String ):Boolean
{
var regExp:RegExp = new RegExp( searchStr, "i" );
return regExp.test( string );
}
}
}
Now you can call that function without instantiating the class anywhere in your app by saying:
StringUtils.contains("this is cool","cool")
Of course, StringUtils must be imported
import some.place.inyourapp.StringUtils
Although it is not recommended, you could use the include operator.
...
include "myFile.as";
...
I need to read the URL that the browser shows when a Flex application is called because I would to reference it in a mxml configuring Cairngorm remote objects.
The goal I would reach is to automatically configure Cairngorm services from environment to environment (dev,test,qa,prod) without statically set the value in the mxml or other ActionScript. Since the Flex client is deployed in the root of the war of the webapp, it's enough to read where the browser is pointing.
I have written a class that is doing so:
public class ConfigServer {
public function ConfigServer() {
var loaderUrl:String = FlexGlobals.topLevelApplication.loaderInfo.loaderURL;
var urlToSet:String = <loaderURL-string-manipulation>;
_serverUrl = urlToSet;
}
private var _serverUrl:String = '';
public function get serverUrl():String
{
return _serverUrl;
}
}
In my mxml I would do so:
<mx:Script>
<![CDATA[
import org.fao.fapda.util.ConfigServer;
private var configuration:ConfigServer = new ConfigServer();
]]>
</mx:Script>
<mx:RemoteObject
id="userService"
destination="userService"
endpoint= "{configuration.serverUrl}/messagebroker/amf"
showBusyCursor="true"
requestTimeout="100"
/>
But whenever I call the ConfigServer constructor and for every (known to me) technique I applied (statics or singletons or public ro so on), I have always had the same error:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at org.fao.fapda.util::ConfigServer()[C:\dev\workspaces\FAPDA\trunk\FAPDA-client\src\org\fao\fapda\util\ConfigServer.as:8]
Cairngorm services initialization is done as follow:
<fx:Declarations>
<cut/>
<services:FAPDAServices id="services"/>
<cut/>
</fx:Declarations>
and the problem is that FAPDAServices.mxml is read runs before FlexGlobals is valid...
Is there a point in the Flex Application lifecycle where such loaderURL is defined so that I can construct ConfigServer? When in startup events that initialization in done?
I confess I'm a Flex epic rookie, so it's possible I'm completely wrong on this.
Best regards
I can't directly answer your question, but hopefully I can point you in the right direction until someone more experienced sees your question.
Create an event handler for the application tag's creationComplete event (or the highest mxml component tag if this is your own custom component) and instantiate ConfigServer there. It is generally neater to do initialization there since it is the last stop before anything is displayed on screen. You can read up more about the event in the adobe live docs. My paraphrasing should never be considered a replacement for official documentation.
You can also use the trace() statement to output text to the console to help you debug the order of execution and whether or not an object has been instantiated. Once again you can check the adobe live docs for more info.
Good luck.
I want to draw something on an <mx:Image> I have in my .mxml file, but I want to keep my drawing implementation in a separate AS class.
How can I access my drawing AS class in my .mxml?
I think what your are asking is how to keep your actionscript files separate from the MXML files that contain your designs. The answer is simple:
Create your actionscript file. Include only methods in this file, and do not wrap the code in a package or class definition. The file should look like the following:
import mx.controls.Alert;
// ActionScript file
/**
*
* Created By jviers
* Created on Apr 14, 2011
*
*
*/
public function hello():Alert{
Alert.show("Hello World!");
}
Create your MXML file that contains your "Design" components. Create a Script element on this mxml file and set the source to the relative path of your ActionScript file. The MXML should look like this:
<?xml version = "1.0" encoding = "utf-8"?>
<s:Application xmlns:fx = "http://ns.adobe.com/mxml/2009"
xmlns:s = "library://ns.adobe.com/flex/spark"
xmlns:mx = "library://ns.adobe.com/flex/mx"
minWidth = "955"
minHeight = "600">
<fx:Script>
<![CDATA[
protected function button1_clickHandler ( event : MouseEvent ) : void {
// TODO Auto-generated method stub
hello ();
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script source = "./scratch/MyFile.as" />
<s:Button label = "Show Alert" click = "button1_clickHandler(event)" />
</s:Application>
You'll notice that the ActionScript in the scratch.MyFile.as is executed when the application is run.
You can use this method to include your drawing logic in your application. The external ActionScript is treated as if it were the method definitions for the class generated by the MXML.
Let me caution you before everyone jumps all over me. This is NOT a best practice. There are specific use-cases in which to use this feature of Flex. Before I get to them let me explain why your notion of keeping "logic" separate from your "view" is inaccurate.
Flex MXML files are not view-only code. They are a declarative dialect that simplifies ActionScript class definitions. When a Flex Project is compiled using mxmlc or compc (those are the compiler programs for flex applications and component libraries, respectively), MXML files are pre-compiled into ActionScript class definitions. If you add the -keep-generated-actionscript directive to your compiler options in Flash/Flex Builder/Ant/command line compile command, the compiler will leave the generated classes that compose the ActionScript class derived from the declaritive MXML files in your project. Thus, an MXML file becomes a class.
Having ActionScript defined in a Script block in your MXML is NOT mixing "logic" with "presentation". Likewise, MXML does NOT define the presentation of your project. It simply is a declarative subset of the ActionScript language that makes it easier to define presentation classes. As proof, you can define ArrayCollections, Strings, and Vectors in MXML. Those classes are data containers and have absolutely nothing to do with presentation.
Now, the reason putting all your ActionScript in external files is not a good thing is that it makes maintaining your project a headache. Not only does someone have to look up your component defined in MXML, but now they have to hunt through the codebase to find the script named Logic.as relatively defined to your component.
The use-cases in which including the external ActionScript via Script.source are the following:
A group of predefined methods/properties are used in lots of components without change. Rather than copy-and-paste those methods into each component, you use the Script.source property to define the methods once and reference them throughout your application.
Similar, but different from use-case-1: You require a mix-in. Like an interface, a mix-in is a set of methods that must be defined for the component to work, and those methods must be reusable and define explicit input parameters and output parameters. Unlike an interface, those methods can be of any namespace type: protected, final, public, internal, mx_internal, etc., and can must function bodies, i.e. have code inside the {} function block. For an example of a "mix-in" think of an enumerable object, an object that has next(), previous(), reset(), and iterator(), methods. When you want to iterate over the object's properties, you call iterator(), which returns an iterator object that calls next() and previous() to fetch the next and previous property values from the object. You can mix this functionality into all kinds of objects and use them usefully. Also, your included functionality is encapsuled within the classes in which it is included. It works like an include directive in AS3.
Hope this helps both your perceptions of what "logic" and "presentation" are in Flex, and helps you solve your particular issue.
I think you have it backwards. If you include the .as file into the .mxml using the <mx:script> tag, you will be able to see the function defined therein.
To address the image, set it an id attribute. From that point, it becomes addressable as if it were defined using ActiveScript like
var image:Image = new Image()
It is no very obvious what relations are between MXML and AS classes you're talking about but the simplest way is create public method in MXML which returns Image. Something like this:
…
<mx:Script>
<![CDATA[
public function getImage():Image
{
return myImage;
}
]]>
</mx:Script>
<mx:Image id="myImage" />
…
So as far as you can refer to your MXML from AS you can call this method.
If you want to draw something in an image by using your own drawing class, i suggest you add it to the constructor of your drawing class, like so:
/*********************************************
* Variables
*********************************************/
private var _myImageIWantToDrawIn:Image;
/*********************************************
* Properties
*********************************************/
public function set image(value:Image):void
{
_myImageIWantToDrawIn = value;
}
public function get image():Image
{
return _myImageIWantToDrawIn;
}
/*********************************************
* Constructor
*********************************************/
public function myDrawingclass(imageYouWantToDrawIn:Image)
{
_myImageIWantToDrawIn = imageYouWantToDrawIn;
}
like this, you can always access the image from that class and draw in it if you want to. (You can also access the _myImageIWantToDrawIn.graphics if you want to draw programmaticaly). you can add the properties if you want to change the image in runtime. you can then simply say: myDrawingclass.image = imageYouWantToDrawIn;
edit: this previous answer was actually the opposite of what you are asking, but I think this will do just fine for what you would want to do. If you want to access your as-class, just make an instance of your class and add public methods to it instead of private ones.
I'm really frustrated in this case.
While developing with Adobe Flex, I'm working on my first application - and use pretty much actionscript.
In my mxml application, I include as3 file via <mx:Script source="as/myas3file.as></mx:Script>.
In myas3file.as, I include (thru include "variables.as";) file variables.as, which contains following code:
var timer:Object = new Object();
timer.t = 60;
or (in other test case)
var timer:Object = {t:60, j:"80"};
timer.t = 80;
Neither case works! Even if I rewrite example code from official documentation, it throws an 1020 error. I'm banging my head to the table for last two hours and I can't figure out what I'm doing wrong.
Thank you
If the code is included from a <Script /> tag in an MXML application, then what you're defining is a member variable and you can't use statements. From the docs:
You use the <mx:Script> tag to insert
an ActionScript block in an MXML file.
ActionScript blocks can contain
ActionScript functions and variable
declarations used in MXML
applications.
...
Statements and expressions are allowed only if they are wrapped in a function. In addition, you cannot define new classes or interfaces in blocks. Instead, you must place new classes or interfaces in separate AS files and import them.
Instead, you can use an initializer as in your second example:
private var name:Object = { field: 80 };
or you can do the initialization in a function (constructor, initialize/creation complete event handler).
I have an FLA file with objects in the library which I have set to be "classes" (In CS3, right click an item in the library select properties, make sure it's set to export for action-script, and has a class name)
For this exercise, let's call the class "MyClass"
If I publish that FLA to an SWC and SWF:
I can load the SWC statically, and instantiate "MyClass" by simply doing:
var inst:MyClass = new MyClasS();
Now, the problem: I'd like to be able to do this at runtime by loading the SWF file using a loader object.
I understand how to access instances which have been created by hand in the FLA before publishing, but what I want to be able to do, is create new instances of the class "MyClass".
I can get a "MovieClip" representing the swf file, I can add it to my displaylist, but I can't seem to get at the classes contained therein. (I hope this makes sense)
Any suggestions for how to attack this would be much appreciated.
Edit : Format code
To complete Christian's answer:
var cls : Class = loader.contentLoaderInfo.applicationDomain.getDefinition("ClassName");
var instance : Object = new cls();
Additionally, it's worth noting that you won't get strong typing (ie. it must be declared as Object) unless the class implements interface which is also defined in your main application. You will then be able to declare the instance variable as the interface and have compile-time access to it's members.
Have a look here; you should be able to extract a class reference by using Loader.contentLoaderInfo.applicationDomain.getDefinition("MyClass").