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

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 :)

Related

How to reference a class in ASP.NET

I created a website and would like to have a class to centralize all the code that I use frequently in the entire project, for instance, a method to connect to the database. Question: after I create this class, on the App_Code folder, how can I use it in the aspx.cs pages? I mean, should a reference it? Should I inform add a namespace?
Thanks!
Create the class file as public and you will be able to access the class file at any part of your project.
namespace applicationName
{
public class DataManager
{
public static DataTable GetData(StringBuilder sql)
{
}
}
}
you can access the DataManager from your code.
DataManager.GetData(SQL);
Yes, put your class in a namespace and consider making the class static if possible, that way it can be used in code throughout your project without instantiating the class. This is common for utility classes that pass in objects and do work with them, but do not need the actual utility method to be part of a class instance.
For example:
namespace My.Utilities
{
public class static ConnectionStringHelper
{
public static string GetConnectionString()
{
// Logic here to actually get connection string
return yourConnectionString;
}
}
}
Now, code in your project just needs to reference the My.Utilities namespace and then can use the GetConnectionString() method, like this:
using My.Utilities;
string connString = ConnectionStringHelper.GetConnectionString();
You can do it a number of ways. Technically you can drop the namespace completely and your code becomes a free for all (accessible from anywhere naturally). I prefer to use namespaces personally, but I have seem people just avoid them.
If your class Foo is in Some.Namespace, you can reference it as such:
Way one:
Some.Namespace.Foo foo = new Some.Namespace.Foo()
Way two: Use the "Use" command
If your class is inside of Some.Namespace and you don't want all the junk preceding your class name, you can add:
using Some.Namespace;
to the top of your file.
I may be miss understanding what you are saying. If you are talking about setup, you can make a centralized class that manages everything. This class can be a singliton. For instance:
class MyClass
{
public static MyClas Singliton;
static MyClass()
{
Singliton = new MyClass();
}
public void someFunction()
{
}
}
This will create and manage a single reference to your class so that everything is managed out of there (hence being called a "singleton"). As a result, you can access it by:
MyClass.Singliton.someFunction();
There are ways to protect your singliton instance from being overwritten, but this is the basic idea. If you want to manage stuff out of a single location without recreating classes, singletons are the way!
http://msdn.microsoft.com/en-us/library/ff650316.aspx
If the class is wrapped in a namespace, then yes, you'll need a using statement that matches your namespace. For instance, if your class is wrapped in a namespace like so:
namespace My.Namespace
{
public class Foo
{
//Methods, properties, etc.
}
}
then anywhere you want to use that class you'll need to add
using My.Namespace;
to the top of the files where you want to utilize the class(es) you've defined. Then you can use your class as you would expect:
Foo foo = new Foo(); //for a new instance
Foo.Bar(); //for a static method
This is, of course, assuming that the class is in the same assembly and you don't want to mess with adding it to the GAC.
Alternatively, if for some reason you don't to use a using statement you can use the fully qualified name of the class:
My.Namespace.Foo foo = new My.Namespace.Foo(); //for a new instance
My.Namespace.Foo.Bar(); //for a static method
This is most useful if you have namespaces that conflict, for instance if you had
namespace My.Namespace
{
public class Foo
{
//Methods, properties, etc.
}
}
somewhere, and
namespace MyOther.Namespace
{
public class Foo
{
//Methods, properties, etc.
}
}
somewhere else, but needed to use them both in the same scope.

use actionscript file in flex library

i want make own flex library and in this library use own actionscript file which will i use in more component in this library..this file contents eg only code
public function computeSum(a:Number, b:Number):Number {
return a + b;
}
but when i can this create just when i click File-New-Actionscript File (filename - OK) is in Problem view Error: A file found in a source-path must have an externally visible definition. If a definition in the file is meant to be externally visible, please put the definition in a package
thanks for help
You should encapsulate it on class, in order to use it with import directive, else u could use it with include
Another approach is to create a "helper" class, or so called "singleton" class.
- a class having only 1 instance, created statically.
on this class u can expose the library functions which u do need and use them everywhere.
package
{
public class Singleton
{
private static var singleton : Singleton
public static function getInstance() : Singleton
{
if ( singleton == null )
singleton = new Singleton();
return singleton;
}
public function Singleton()
{
}
public function visibleTroughtTheSingletonfunction( arg1 : int ... ) : void
{
}
public static function directlyVisiable() : void
{
}
}
}
the accessing the singleton would be something like :
Singleton.getInstance.visibleTroughtTheSingletonfunction( 1 );
OR
Singleton.directlyVisiable();
depending on your needs.
Well first you'll need to create a class (and a package) and put that method inside that (not just into an empty AS file) and second if you want to be able to access the method without creating an instance of the class make this method static.
If you don't need to change the class file during runtime then make action class compile into swc library.
create a Action script project and compile it in the bin folder you found the .swc library file. include that .swc into your project .

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.

Singleton Class in Flex

I have a doubt,.... How would you create a Singleton class in Flex...
Is there any convention like the class name should eb Singleton or it should extend any other class.
How many Singleton class can a project have?
Can anyone say the real time usage of a Singleton class?
I am planning to keep my components label texts in a Singleton class... Is it a good approach.
Can of worms asking about singletons!
There are a few different options about creating singletons mainly due to AS3 not having private constructors. Here's the pattern we use.
package com.foo.bar {
public class Blah {
private static var instance : Blah;
public function Blah( enforcer : SingletonEnforcer ) {}
public static function getInstance() : Blah {
if (!instance) {
instance = new Blah( new SingletonEnforcer() );
}
return instance;
}
...
}
}
class SingletonEnforcer{}
Note that the SingletonEnforcer class is internal so can only be used by the Blah class (effectively). No-one can directly instantiate the class, they have to go through the getInstance() function.
hope I'm not hitting dead horses here :)
(edit: ahh, I'm just repeating phils link)
Gregors singleton implementation does not protect against invoking the constructor with a null value, as in:
var b:Blah = new Blah(null);
You will still have only 1 instance, but invoking the constructor is still possible with the consequences that follows.
If you absolutely must enforce the singleton, the constructor should make sure that the enforcer parameter isn't null.
public function Blah( enforcer : SingletonEnforcer ) {
if(!enforcer){
throw new Error("whoops!");
}
}
You should also be concerned about ApplicationDomain when loading swf files. External swf files that uses the same definitions, may have multiple singleton instances (1 in each separate applicationdomain) if you do not specify that the swf file must be loaded into the existing applicationdomain.
This means that Blah.getInstance() in AAA.swf is not the same instance as Blah.getinstance() in BBB.swf, if AAA.swf loads BBB.swf without a LoaderContext instance that tells the plugin to load BBB.swf into the same ApplicationDomain as AAA.swf
First you can reference a previous question to find out how to create a singleton class. You can find more info from a Yakov Fain presentation as well.
Second question, your project can technology have as may singleton class as you see fit but it will only create 1 instance of each. For example, in the cairngorm architecture you have 3 main singletons: controller, service and model. The number of actual class can very depending on your project.
Finally, A real world solutions would be. You have 2 components that need to talk to each other but you don't want them to know the other exists. Meaning sometimes the components are there and sometimes they are not...so you need them to be loosely coupled. you can uses singletons to pass the data from one component to the other with out "talking" to them directly.
Using singletons is a good approach if you need to pass data around your application from component to component and would like to decouple them from each other.
package com.foo.bar
{
public class MySingleton
{
private static var _instance:MySingleton = new MySingleton;
private var _myName:String;
public static function get instance():MySingleton
{
return _instance;
}
public function set myName(value:String):void
{
_myName = value;
}
public function get myName():String
{
return _myName;
}
}
}
Notice the absence of a constructor here.
Hello you could check out the following of a Flex Singleton Class example on http://www.how-to-code.com/flex/flex-design-patterns/flex-singleton-class.html

Resources