Can't inherit from classes defined in an RSL? - apache-flex

Note: This is an Actionscript project, not a Flex project.
I have class A defined in an RSL (technically, it's an art asset that I made in the Flash IDE and exported for actionscript. The entire .FLA was then exported as a SWC/SWF).
I my main project I have class B, which inherits from class A. The project compiles fine, with no errors.
However, when when the project runs and I try to create an instance of Class B, I get a verify error. Creating an instance of Class A works just fine, however:
import com.foo.graphics.A; // defined in art.swf / art.swc
import com.foo.graphics.B; // defined locally, inherits from A
...
<load art.SWF at runtime>
...
var foo:A = new A(); // works fine
var bar:B = new B(); // ERROR!
// VerifyError: Error #1014: Class com.foo.graphics::A could not be found.
For reference, here is how I'm loading the RSL:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onArtLoaded);
var request:URLRequest = new URLRequest("art.swf");
var context:LoaderContext = new LoaderContext();
context.applicationDomain = ApplicationDomain.currentDomain;
loader.load(request, context);
Class B is defined as follows:
import com.foo.graphics.A;
class B extends A {}

I don't think this is a bug. It's more a linkage problem.
The verifier error doesn't happen when you try to create an instance of B. It happens as soon as your main swf is loaded and verified by the player. This is an important distinction. To see what I mean, change this code:
var bar:B = new B();
to
var bar:B;
You'll still get the error.
I don't know how you are builing the swf, but from the error it seems evident that the A class (B's parent) is being excluded from the swf. I can reproduce this using this mxmlc switch:
-compiler.external-library-path "lib.swc"
However, changing it to:
-compiler.library-path "lib.swc"
The problem goes. Obviously, this kind of defeats the purpose of loading the assets at runtime, since these assets are already compiled into your main.swf (in fact, it's worse, because by doing that you've just increased the global download size of your app).
So, if you set your art lib as external, the compiler can do type checking, you'll get auto-complete in your IDE, etc. Your B class still depends on A being defined, though. So, at runtime, A has to be defined whenever B is first referenced in your code. Otherwise, the verifier will find an inconsitency and blow up.
In the Flash IDE, when you link a symbol, there's a "export in first frame" option. This is how your code is exported by default, but it also means it's possible to defer when the definition of a class is first referenced by the player. Flex uses this for preloading. It only loads a tiny bit of the swf, enough to show a preloader animation while the rest of the code (which is not "exported in first frame") and assets are loaded. Doing this by hand seems a bit cumbersome, to say the least.
In theory, using RSL should help here if I recall correctly how RSL works (the idea being the a RSL should be loaded by the player transparently). In my experience, RSL is a royal pain and not worth the hassle (just to name a few annoying "features": you have to hard-code urls, it's rather hard to invalidate caches when necessary, etc. Maybe some of the RSL problems have gone and the thing works reasonably now, but I can tell you I've been working with Flash since Flash 6 and over the years, from time to time I'd entertain the idea of using RSL (because the idea itself makes a lot of sense, implementation aside), only to abandon it after finding one problem after the other.
An option to avoid this problem (without using RSL at all) could be having a shell.swf that loads the art.swf and once it's loaded, loads your current code. Since by the time your code.swf is loaded, art.swf has been already loaded, the verifier will find com.foo.graphics.A (in art.swf) when it checks com.foo.graphics.B (in code.swf).
public function Shell()
{
loadSwf("art.swf",onArtLoaded);
}
private function loadSwf(swf:String,handler:Function):void {
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, handler);
var request:URLRequest = new URLRequest(swf);
var context:LoaderContext = new LoaderContext();
context.applicationDomain = ApplicationDomain.currentDomain;
loader.load(request, context);
}
private function onArtLoaded(e:Event):void {
loadSwf("code.swf",onCodeLoaded);
}
private function onCodeLoaded(e:Event):void {
var li:LoaderInfo = e.target as LoaderInfo;
addChild(li.content);
}
In your current main class, add this code:
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
Move your constructor logic (if any) to the init method, and it should work fine.
But what I don't like about this approach is that you have to create another project for the shell.
What I do, generally, is have a class that proxies the graphic asset.
private var _symbol:MovieClip;
public function B() {
var symbolDef:Class = ApplicationDomain.currentDomain.getDefinition("com.foo.graphics.A") as Class;
_symbol= new symbolDef();
addChild(_symbol);
}
Since com.foo.graphics.A is just a graphical asset, you don't really need to proxy other stuff. What I mean is, if you want to change x, y, width, etc, etc, you can just change these values in the proxy and the result is in practice the same. If in some case that's not true, you can add a getter / setter that actually acts upon the proxied object (com.foo.graphics.A).
You could abstract this into a base class:
public class MovieClipProxy extends MovieClip {
private var _symbol:MovieClip;
public function MovieClipProxy(linkagetName:String) {
var symbolDef:Class = ApplicationDomain.currentDomain.getDefinition(linkagetName) as Class;
_symbol = new symbolDef();
addChild(_symbol);
}
// You don't actually need these two setters, but just to give you the idea...
public function set x(v:Number):void {
_symbol.x = v;
}
public function get x():Number {
return _symbol.x;
}
}
public class B extends MovieClipProxy {
public function B() {
super("com.foo.graphics.A");
}
}
Also, injecting the app domain as a dependency (and moving the instantiation mechanism to other utility class) could be useful for some projects, but the above code is fine in most situations.
Now, the only problem with this approach is that the linkage name in the constructor of B is not checked by the compiler, but since it's only in one place, I think it's manageable. And, of course, you should make sure your assets library is loaded before you try to instantiate a class that depends on it or it will trhow an expection. But other than that, this has worked fairly well for me.
PS
I've just realized that in your current scenario this could actually be a simpler solution:
public class B extends MovieClip {
private var _symbol:MovieClip;
public function B() {
_symbol = new A();
addChild(_symbol);
}
}
Or just:
public class B extends MovieClip {
public function B() {
addChild(new A());
}
}
The same proxy idea, but you don't need to worry about instantiating the object from a string using the application domain.

Related

Access objects instantiated in Flex app's MXML file in other AS classes

I've got an object declared and instantiated in my Flex application's singular MXML file:
public var CDN:CDNClass = new CDNClass;
I would like to access this same CDN object (and its public methods and properties) in another class declared in a separate .as file as such:
package my.vp
{
import my.media.CDNClass;
public class SyncConnectorManager
{
private function syncMessageReceived(p_evt:SyncSwfEvent):void
{
switch (p_evt.data.msgNm)
{
case "startStream" :
// Play a stream
CDN.parsePlayList(p_evt.data.msgVal);
break;
But when I try to access the public method parsePlayList in the CDN object in a method in the class defined in the .as file, I get the following error:
Access of undefined property CDN
The reason I want to do this is to break up the logic of my application into multiple AS files and have minimal MXML files, probably only one.
Thanks - any help is much appreciated. Perhaps my OOD/OOP thinking is not correct here?
IT depends on your class architecture. For your code to work, the CDNClass instance must be defined and implemented inside your SyncConnectorManager.
Generally, you can always call down into components, but should never call up
One option is to pass the instance ofCDNClass to a variable inside SyncConnectorManager. Add this variable to your SyncConnectionManager class:
public var CDN:CDNClass = new CDNClass;
And at some point do this:
syncConnectorManagerInstance.CDN = CDN;
That way both classes will have access to the same CDN instance and can call methods on it.
Yes, your OOP thinking is not correct here. You should take in mind differences between classes and instances. This line declares a filed in a current class and initiates it with an instance:
public var CDN:CDNClass = new CDNClass;
So current instance of your MXML class (you can think about it as usual AS class with some other notation) has public field. To operate with CDN instance you need something from the following:
Read the value of CDN (as far as it is public) from the instance of your MXML class. You need some reference to it for that.
The instance of your MXML class can have a reference to the instance of SyncConnectorManager and SyncConnectorManager should have a way to inject the value of CDN there. Something like:
Your class:
package my.vp
{
import my.media.CDNClass;
public class SyncConnectorManager
{
private var CDN:CDNClass;
public function SyncConnectorManager(CDN:CDNClass)
{
this.CDN = CDN;
}
private function syncMessageReceived(p_evt:SyncSwfEvent):void
{
switch (p_evt.data.msgNm)
{
case "startStream" :
// Play a stream
CDN.parsePlayList(p_evt.data.msgVal);
break;
In your case SyncConnectorManager class hasn't CDN declared (the problem of the compiler error you mentioned) and instantiated (the problem of NPE even if you just declare field).
As the bottom line I can suggest you to follow ActionScript naming and coding conventions to talk other people and team members about your code :)

How do you access the public properties and methods of a loaded SWF

How would you go about calling the public properties and methods of a SWF you load in actionscript?
I have been using stackoverflow for years to answer my programming questions so I wanted to give back by writing a guide to an issue I had a lot of trouble figuring out. This is my first user guide so tell me if there is anything I can do to improve it.
One of the more powerful features of the flash engine is the ability to load flash programs within flash programs, through the use of the Loader class. Unfortunately communication with the loaded program is limited. While you can establish a LocalConnection object there is a limit to the traffic it can safely support.
A simple solution is to load the SWF file within your main program’s security domain. This has the benefit of exposing the public methods and properties of the loaded SWF to the loader and vice versa.
First extend the Loader class this class will be used to interact with the loaded file.
public class ParentChildLoader extends Loader
Next we must store the SWF file as a ByteArray. The variable path is a file path on the system. You could use a URLStream object instead of a FileStream for a http url.
var swfBytes:ByteArray = new ByteArray();
var file:File = new File(path);
if (file.exists)
{
var loadStream:FileStream = new FileStream();
loadStream.open(file, FileMode.READ);
loadStream.readBytes(swfBytes);
loadStream.close();
}
Now that we have the SWF stored as a ByteArray, we load the SWF into our security domain and listen for the complete event.
var context:LoaderContext = new LoaderContext();
context.allowLoadBytesCodeExecution = true;
addEventListener(Event.COMPLETE, onSwfLoad);
loadBytes(swfBytes, context);
If you want to access the loaded SWF’s properties from the loader use the content property.
Object(this.content).foo(bar);
Object(this.content).a = b;
If you want to access the loader’s public properties from the SWF use the parent property.
Object(this.parent).foo(bar);
Object(this.parent).a = b;
This has many practical applications from allowing re-usability of common functions to taking some of the programming load off your creative team. A note of caution; the loaded SWF exists within your main program’s security domain so it is key that you only load files which you trust with this method.
A cleaner way would be to use interfaces. Here's an example. Consists of two projects. Project 1 (PluginLoader) is your base app. Part of this project includes an AS3 Interface:
/* IPlugin.as */
package
{
public interface IPlugin
{
function getID():String;
function doStuff():void;
}
}
Then, your loaded swf in a second project (TestPlugin) implements the interface:
package
{
import flash.display.Sprite;
public class TestPlugin extends Sprite implements IPlugin
{
private const _ID:String = "TestPlugin";
public function getID():String {
return _ID;
}
public function doStuff():void {
trace('Test plugin: Doing Stuff');
}
}
}
The interface would be included in that project via source files or swc.
Then to load it (back in PluginLoader project):
public class PluginLoader extends Sprite
{
public function PluginLoader()
{
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
loader.load(new URLRequest('plugins/TestPlugin.swf'));
}
private function completeHandler(e:Event):void {
var plugin:IPlugin = e.target.content as IPlugin;
trace(plugin.getID());
plugin.doStuff();
}
}
}
I would have to disagree with you on your approach. It is 'hackish' in my opinion. There is a reason why you have limited communication with loaded swfs, and that is because you don't know what they do and how they're suppose to be managed.
If you want to talk architecturally, this is a very bad way of trying to access information. The main application should not have to access properties within the loaded swf. If you're building a large scale application and the loaded swf (a module maybe?) needs information that the main app has, you should look into an application framework like Parsley which does dependency injection to give the data your loaded swf needs. It is a much cleaner approach and is architecturally sound.

Can I control multiple instances of movieclips in a loaded swf at once?

I am loading an swf created in flash professional cs5 via the loader class into a flex 4.1 application. The flash file contains multiple movieclips that are exported for actionscript and those movieclips exist in many instances throughout the movie.
Iterating through everything, comparing class types seems to be the most easy but also the most redundant way to solve this. Is there any way of using the class name as a kind of global selector to access the clips?
I could also make the sub-clips in the flash listen for an event on which they perform an action, but I am not really sure what might be best.
In cases like these, I find that a good way to solve the problem is to create a statically accessable class that manages instances of other classes that are registered with it on instantiation. As an example...
public class GlobalStopper{
private static var clips:Array = [];
public static function add(mc:MovieClip):void{
clips.push(mc);
}
public static function stop():void{
var mc:MovieClip;
for(var i:int = 0, ilen:int = clips.length ; i < ilen ; i++){
mc = clips[i] as MovieClip;
if (mc) mc.stop();
}
}
}
and...
public class GloballyStoppableMovieClip extends MovieClip{
public function GloballyStoppableMovieClip(){
GlobalStopper.add(this);
}
}
Any and all instances of GloballyStoppableMovieClip are instantly registered with the GlobalStopper, so calling
GlobalStopper.stop();
...will stop all registered movieclips.
You can add in any other functions you want. Furthermore, instead of having add accept MovieClip instances, you could have it accept IStoppable or IPlayable objects that implement public functions stop() and play() that your movieclip subclass (or non-movieclip object that also might need to stop and play!) then implements.
But as for jQuery-like selectors? Not really the way I'd handle this particular issue.
i guess typing it out did the trick. i used the event solution:
in the root timeline i placed a function like this:
function cause():void {
dispatchEvent(new Event("do stuff",true));
}
and in the library clip's main timeline goes:
DisplayObject(root).addEventListener("do stuff", function (e:Event=null) {
... whatever ...
});
this is dirty but you get the idea.

Flex: How to use flashvars from different classes

I am just learning actionscript, so come across the problem
In my application I often call to different web services, and because I don't want to hardcode urls to them in my code, I am passing urls to the services as flashvars.
Currently I am doing it this way:
public var siteUrl:String;
public var gameId:String;
public function main():void
{
siteUrl = Application.application.parameters.siteurl;
gameId = Application.application.parameters.gameid;
Where main is a function, which is called on application's creation complete event.
This way I can call both variables from main file of the application but I want to access them from other files. (other as classes)
So is there a way to create class with constants and init values there with flashvars so I can use them everywhere (after importing of course)
The parameters are just stored in that Application.application.parameters object, and that's static. There's no reason you couldn't access that from other classes in your code.
If you want to write a class that wraps the parameters (maybe validates them or something) you could do that fairly easily. You can use a for each loop to loop over all the parameters. Something like:
var params:Object = Application.application.parameters
for(var name:String in params) {
var value:String = params[name] as String;
/* do something with the param */
}
If you want your class to actually verify things then it could just check for each parameter it expects and store it in a local variable.
It really just depends on your own preferences. Some people are fine with accessing the parameters object when they need it. Some people like having the extra code-completion by having a config class that actually defines all the expected config variables.
Update in response to comment:
Instead of having one module declare the variable and have other modules have to depend on that one to access the property it would be cleaner to have a single config module that everything that needs it would all use.
You could use a static class or singleton or some IoC stuff. Just for simplicity I'll show you a way you can do it with a static class.
class MyConfig {
private static var _infoService:String;
private static var _someOtherParam:int;
public static function get infoService():String { return _infoService; }
public static function get someOtherParam():int { return _someOtherParam; }
public static function initParams():Void {
var params:Object = Application.application.parameters;
_infoService = params.infoservice;
// just assuming you have a method to convert here. don't remember the
// code off the top of my head
_someOtherParam = convertToInt(params.someOtherParam);
}
}
Make sure when your app initializes it calls MyConfig.initParams(). You can have that method actually validate that it gets everything it expects and throw exceptions (or return an error) if there's a failure if you want.
Then wherever you need to use that config within your code you just import your config class and access the param. So getting infoService would just be:
var infoService:String = MyConfig.infoService;
Personally I wouldn't use a static class, but it was the easiest to show.

Create Plugins in Flex - loading nested SWF files

I'm trying to implement a plugin system for our application, and having a devil of a time getting SWF file which was dynamically loaded itself, load additional SWF files.
It goes something like this:
Main Application Shell loads...
---------+ Application loads...
-----------------+Plugin(s)
I have no problem getting app #1 to load app #2
However, try as I might, I cannot get app #2 to load and instantiate #3
I've tried various permutations using the ModuleManager, but this is the closest I get. When the onLoadComplete method get invoked, I can see that the SWF loaded, however the factory always returns NULL.
What is interesting is that when I extract this out in its own application, it works fine. This issue is triggered by the fact that I'm loading Plugin from a SWF that was loaded dynamically itself.
I believe this is due to the ApplicationDomain, but I cannot make heads or tails of it. I tried specifying currentDomain, new ApplicationDomain(Application.currentDomain) and new ApplicationDomain() without success.
Also, it is important to note that I cannot make reference a hard reference to the Foo class in either applications since by their nature, we will not know ahead of time what they will contain.
Googlin' around, this seems to be a fairly known problem, but I have not found a (clear) solution yet.
.
.
.
assetModule = ModuleManager.getModule("Foo.swf");
assetModule.addEventListener(ModuleEvent.READY, onLoadComplete );
assetModule.addEventListener(ModuleEvent.ERROR, onLoadError);
assetModule.load();
.
.
.
private var _pluginInstance:Plugin;
private function onLoadComplete( event:Event ):void
{
trace("module loaded");
_pluginInstance = assetModule.factory.create() as Plugin;
if( _pluginInstance )
_pluginInstance.startup();
else
Alert.show("unable to instantiate module");
}
private function onLoadError( event:Event ):void
{
Alert.show("error");
}
My Plugin looks like this:
package
{
import mx.collections.ArrayCollection;
import mx.modules.ModuleBase;
public class Plugin extends ModuleBase
public function startup():void
{
}
.
.
.
}
and
package
{
import Plugin;
import mx.modules.ModuleBase;
public class Foo extends Plugin
{
public function Foo()
{
trace("foo constructor invoked");
}
override public function startup():void
{
trace("foo started");
}
.
.
.
}
# joshtynjala is right. I found try just using Object then calling methods on it (don't cast).
var MyPlugin : Object = getPlugin();
MyPlugin.doPluginFunc();
Generally can cast between system/flex classes no problem. Don't know if putting Plugin as a runtime library would help ?
If you really want to use a common interface between your plugin and your application, your application's Plugin class must be the same as your plugin's Plugin class. To do so, they need b to be in the same ApplicationDomain.
//In an external library
public interface Plugin {}
//In your application
_pluginInstance = assetModule.factory.create() as Plugin;
...
//In your plugin
public class MyPlugin implements Plugin
The problem is, when you will compile your plugin swf, you will also compile Plugin. This is not a problem, but you need to tell your application that it's the same as his :
var loader:Loader = new Loader();
loader.addEventListener(Event.COMPLETE, onLoadComplete);
loader.load(new URLRequest("plugin.swf"), new LoaderContext(false, ApplicationDomain.currentDomain));
ApplicationDomain.currentDomain is the key here. If you refer to the docs :
Loader's own ApplicationDomain. You
use this application domain when using
ApplicationDomain.currentDomain. When
the load is complete, parent and child
can use each other's classes directly.
If the child attempts to define a
class with the same name as a class
already defined by the parent, the
parent class is used and the child
class is ignored.

Resources