Accessing a variable defined by a constructor function through another class - actionscript-3

I have two classes, the first one is called CoreModus. In CoreModus (which is a non-document class) I declare a "global" variable, called modus, using the constructor function CoreModus(modus);
CoreModus.as:
package myStudio.basic {
public class CoreModus {
public var modus:String;
public function CoreModus(structure:String) {
modus = structure;
}
public function setup():String {
return modus;
}
}
}
The second class is called Animation, which is a non-document class, and I want to access the variable modus, which is declared in CoreModus constructor function: i.e CoreModus("non-linear"); which in this case modus = non-linear.
Animation.as:
package myStudio.basic {
import fl.transitions.Tween
public class Animation {
public var anim:Tween;
public function Animation() {}
public function tryToRetrieveModus():void {
var modo:CoreModus = new CoreModus();
var modus:String = modo.getModus();
trace("I'm trying to retrieve the modus " + modus);
}
}
}
Of course, because CoreModus needs a parameter, I can't use the option I tried in Animation.as (making an instance of CoreModus).
FLA document, frame 1:
import myStudio.basic.CoreModus;
import myStudio.basic.Animation;
var modo:CoreModus = new CoreModus("non-linear");
var mov1:Animation = new Animation();
trace(modo.setup());
mov1.tryToRetrieveModus();
Is there any other way to access to this variable?
P.S. I omitted a bunch of unrelated lines in CoreModus(); constructor function. I don't want that code to be processed every time, for CPU's sake.

To access the variable from your CoreModus class instance, first create the instance of the class somewhere.
Then, pass the instance reference to the the Animation class instance. After that you can use the public variable of CoreModus as you please.
Here's an example:
//creating the CoreModus class instance
var myCoreModus:CoreModus = new CoreModus("my string");
//creating the Animation class instance
var myAni:Animation = new Animation();
myAni.modo = myCoreModus; // make sure that modo is public instance variable
You can also make your CoreModus a singleton and have a static variable if you have only one instance of your CoreModus.

Related

AS3 : Dynamic text field text doesnt update (returns to default text)

I have a movieclip with a dynamic TextField in it, it has the text "Software part" in it by default. In the class of this movieclip I have the following code:
package {
import flash.display.MovieClip;
import flash.text.TextField;
public class soft_4 extends MovieClip {
public static var software_part_4_text:TextField;
public static var software_part_4_text_bg:String;
public static var software_part_4_text_tu:String;
public static var software_part_4_text_li:String;
public static var software_part_4_text_de:String;
public function soft_4() {
// constructor code
software_part_4_text_bg = "Софтуерна част";
software_part_4_text_de = "Software-Teil";
software_part_4_text_tu = "Yazılım bölümü";
software_part_4_text_li = "Programinės įrangos dalis";
software_part_4_text = software_part_4;
software_part_4_text.selectable = false;
}
}
}
I have an instance of this class in my Main class and depending on a button press, the strings in the TextField are changed like so:
soft_4.software_part_4_text.text = soft_4.software_part_4_text_de;
For instance that changes the text in the TextField to be in German. It works for the first instance of this class (for example: public var firstInstance:soft_4 = new soft_4()) that I have on stage BUT the second instance (for example: public var secondInstance:soft_4 = new soft_4()) has the default text which is "Software part".
I've embedded the font that I am using in the text field.
You seem confused about the way static variables work. When you set the static variable software_part_4_text, all you are doing is setting a static reference to an instance object. Each time you call new soft_4(); you are making a new instance of that class. And each one of those instances has it's own TextField instance software_part_4. Each instance is unrelated to all the rest.
So this line software_part_4_text = software_part_4 is just setting a static reference to your instance variable. It does not make all of your instances to be the same. When you change the text property of the static reference, you are only updating that single instance. This will NOT have any effect on all the other instances.
What you need to do is update each particular instance separately. If you want to do this with a single call, you pretty much need to store a reference to all of the instances. You could do this with an array and a loop, like so:
public class soft_4 extends MovieClip {
//Make a static reference to a String, instead of a Textfield
//This can be private, as it will only be used internally
private static var software_part_4_text:String;
//Should these be Constants??
public static var software_part_4_text_bg:String = "Софтуерна част";
public static var software_part_4_text_tu:String = "Yazılım bölümü";
public static var software_part_4_text_li:String = "Programinės įrangos dalis";
public static var software_part_4_text_de:String = "Software-Teil";
//This is the Vector used to store all the instances.
//This can be private, as only this class will ever need to know about it.
private static var _instances:Vector.<TextField> = new Vector.<TextField>();
public function soft_4() {
// constructor code
software_part_4.selectable = false;
//Each time a new instance is created, store it in the vector.
_instances.push(software_part_4);
}
//This is the static function you would call from your main timeline or whatever.
//Pass in the string that you want the new Text to be
public static function UpdateAllTextFields(newText:String):void
{
software_part_4_text = newText;
_instances.forEach(updateTextField);
}
//This is the function that is executed over each instance in the Vector
private function updateTextField(tf:TextField, index:int, vector:Vector.<TextField>):void {
tf.text = software_part_4_text;
}
}
Then from your Main class you could write something like this:
soft_4.UpdateAllTextFields(soft_4.software_part_4_text_de);
I haven't tested this, nor I have I written any AS3 in a very long time, so let me know if it doesn't work

Get stage in ActionScript-3 without a DisplayObject?

How can I get a reference to my stage without having a Sprite/DisplayObject that is added to the stage already ?
More info: I have a static class that is a utility class and I want it to initialize in static class constructor but I also need the reference to the stage.
public class UtilClass
{
trace("init: " + stage);
}
First thing that is called in my AS-3 apps is the constructor of my main Sprite/DisplayObject and it has access to the stage. So the stage exists at that point. Then I call utility methods of my UtilClass. Now I want it to initialize by itself on the first use (when stage is already in existance).
I want to know if stage object can be accessed from anywhere without being initialized from outside of the utility class.
Edit:
public class SimpleSprite extends Sprite
{
public static var aaa:int = 12;
public static function test():void
{
trace("here I am");
}
trace(aaa, Capabilities.screenResolutionX+", "+Capabilities.screenResolutionY);
test();
}
The stage reference is available in your MainTimeline or Main instance, depending on platform. You can add code there to pass that reference to other classes should you need it. The class should have a method (static, in your case) that'll accept a Stage parameter and store it somewhere inside the class.
public class UtilClass {
private static var theStage:Stage=null;
public static function initialize(s:Stage):void {
if (theStage) return; // we're initialized already
theStage=s;
}
// once you call this, you can "trace(theStage)" and get correct output
// other methods can also rely on theStage now.
}
Then you call UtilClass.initialize(stage); and you're set.
You will need to initialise your UtilClass and pass the stage reference. I recommend you to have a Class only for 'manage' Stage reference.
You could try something like this (just a quick example):
public class StageReference
{
public static const STAGE_DEFAULT:String = 'stageDefault';
protected static var _stageMap:Dictionary;
public static function getStage(id:String = StageReference.STAGE_DEFAULT):Stage
{
if (!(id in StageReference._getMap()))
throw new Error('Cannot get Stage ("' + id + '") before it has been set.');
return StageReference._getMap()[id];
}
public static function setStage(stage:Stage, id:String = StageReference.STAGE_DEFAULT):void
{
StageReference._getMap()[id] = stage;
}
public static function removeStage(id:String = StageReference.STAGE_DEFAULT):Boolean
{
if (!(id in StageReference._getMap()))
return false;
StageReference.setStage(null, id);
return true;
}
protected static function _getMap():Dictionary
{
if (!StageReference._stageMap) StageReference._stageMap = new Dictionary();
return StageReference._stageMap;
}
}
When you start your application (Main Class or where you start to include your logic)
StageReference.setStage(stage);
And when you need to get the stage reference
trace('Checking the Stage: ', StageReference.getStage());

as3 class getting dynamic vars from another class

I am going to simplify my question. I need to create a list of vars that have defaults but
they can change with clicks etc. Default Vars stored in (defaultVars.as)
These default vars are created in this class that is loaded via the main.as class. I have another class (getVars.as) that needs to access the vars that are changing. How can this new class have access to dynamic vars?
Thanks
If you have your class that holds these variables instantiated in the Main class, you can pass reference to it to the constructor of the secondary class that you want to have access its properties.
Small example:
The class holding variables:
class AppModel
{
public var test:int = 10;
public var something:String = "hello";
}
The class needing access to those variables:
class Component
{
public function Component(appModel:AppModel)
{
appModel.something = "changed";
trace(appModel.test); // 10
}
}
And the main class:
class Application
{
private var _appModel:AppModel;
private var _component:Component;
public function Application()
{
_appModel = new AppModel();
_component = new Component(_appModel);
trace(_appModel.something); // changed
}
}

How to Make Popup window as Global in Flex?

Actually in my Flex Application have Some Popup windows and i want take some values in this Popup Window But The Values are Comming NULL
So how to Make a PopUp Window as Global? Because we are Using the values Globally.
Please Give Suggestion...
Edit
I'm Edit with some code...
Main.mxml(Main Aplication), Demo1.mxml(PopUpWindow), Demo2.mxml(PopUpWindow)
Now in Demo1.mxml have variable like...
[Bindable]private var arrayC:ArrayCollection=new ArrayCollection();//Hear Some value their.
NOw i want Use arrayC in Demo2.mxml then ..
public var variable1:Demo1=new Demo1();
var ac:ArrayCollection = new ArrayCollection();
ac = variable1.arrayC;
But hear ac contain Null Value Why?
Then,Now i'm Thinking Demo2.mxml(PopUpWindow) is Converting To Global Scope so it's value Used in Any Where .
Null because of you are tried create new instance so that each instance having their own state.
Also i bet you can't access arrayC ArrayCollection variable declared as private so you can't acccess.
Need to follow few steps
[Bindable]public var arrayC:ArrayCollection=new ArrayCollection(); //Make public variable
Use Singleton Class for you application
package com.foo.bar {
public class Model {
private static var instance : Model;
public function Model( enforcer : SingletonEnforcer ) {}
public static function getInstance() : Model {
if (!instance) {
instance = new Model( new SingletonEnforcer() );
}
return instance;
}
public var arrayC:ArrayCollection = new ArrayCollection();
}
}
class SingletonEnforcer{}
For more details Singleton pattern
private var popup:Demo1;
popup = PopUpManager.createPopUp(this,Demo1,true) as Demo1;
popup.arrayC = Model.getInstance().arrayC; // Here set value from Model class
PopUpManager.centerPopUp(popup);
Suppose you tried to access demo1.mxml arrayC variable in Demo2.mxml
var demo1_arrayC = Model.getInstance().arrayC;
Note that you can access arrayC arraycollection anywhere in your application like Demo2.mxml,Demo3...etc.
But better we have to avoid Singleton Class (unit test diffcult ..etc).
If you are using the values Globally, then no matter what you mean by the "Make a PopUp Window as Global", I strongly suspect that you would be best served by a singleton event dispatcher.
package com.example.demo.models {
import flash.events.IEventDispatcher;
import flash.events.EventDispatcher;
[Bindable]
class MyGlobalStuff extends EventDispatcher {
public var someGlobalValue:*;
private var _instance:MyGlobalStuff;
public function MyGlobalStuff (lock:SingletonLock, target:IEventDispatcher=null) {
super(target);
if(!(lock is SingletonLock)) {
throw(new Error("MyGlobalStuff is a singleton, please do not make foreign instances of it"));
}
}
public static function getInstance():MyGlobalStuff {
if(!_instance) {
_instance = new MyGlobalStuff (new SingletonLock());
}
return _instance;
}
}
}
class SingletonLock{}
The idea is this: that you would bind in your popup to
{myStuffModel.someGlobalValue}
myStuffModel would be initialized in your mxml as:
protected var myStuffModel:MyStuffModel = MyStuffModel.getInstance();
then in any other class throughout your application you can bind to or access the EXACT same data via the singleton model.

ActionScript3: Inheriting constructor arguments from parents

I'm making a game in action script 3. In it, I have an actor class from which player and enemy classes will be derived. I'm doing this so that unless I need to provide specific AI or fancy behavior (such as for bosses), I can just make a new clip in the library for each enemy without making an actionscript file.
However, I've run into a problem.
Whenever I try to pass arguments to the construction of an enemy (make it spawn with more health), I get error 1136 (Incorrect number of arguments.)
This is because the constructor created automatically at runtime doesn't have the same arguments as it's parent class. Is there any way to get around this without making a class file where I copy and paste the parent constructor function for each of my hundreds of enemies?
Edit
actually rereading your question I think you may be looking for super();
Example
public class Actor{
private var myHelth:uint;
public function Actor(helth:uint = 100){
myHelth = helth; //this will be set to 100 if nothing it passed in or the value passed
}
}
Class that extends Actor:
public class Boss extends Actor{
public function Boss(){
super(200); //passes 200 to Actor;
}
}
If you're trying to pass data into a classes constructor you need to make sure it's accepting arguments.
public class Actor{
private var myHelth:uint;
public function Actor(helth:uint = 100){
myHelth = helth; //this will be set to 100 if nothing it passed in or the value passed
}
}
Then to use
var a:Actor = new Actor(200); //setting health to 200
var b:Actor = new Actor(); //using the default of 100
Make sure your symbols in Flash Pro have appropriate AS linkage, then use pass constructor arguments in super statements:
Actor - base class
package
{
public class Actor
{
public function Actor(name:String, role:String)
{
}
}
}
Player - inherits from Actor defining its own constructor parameters:
package
{
public final class Player extends Actor
{
public function Player(... params:Array)
{
// pass desired inherited constructor parameters
super("name", "role");
}
}
}
Enemy - inherits from Actor defining its own constructor parameters:
package
{
public final class Enemy extends Actor
{
public function Enemy(... params:Array)
{
// pass desired inherited constructor parameters
super("name", "role");
}
}
}