Calling methods from another class Action Script 3 - actionscript-3

I have two classes called 'main' and 'TimerCountDown'. I was try to call a single function 'reset' from 'TimerCountDown' in 'main' class.
This is my TimerCountDown class:
public class TimerCountDown extends MovieClip
{
public function TimerCountDown(t:TextField, timeType:String, timeValue:Number, es:String, _documentclass):void
{
this.documentclass = _documentclass;
this.tfTimeDisplay = t;
if (timeType == "seconds")
{
this.timeInSeconds = timeValue;
}
if (timeType == "minutes")
{
this.timeInSeconds = timeValue * 60;
}
this.tfEndDisplayString = es;
this.startTimer();
}
public function reset():void{
clockCounter.reset();
}
}
How can I create a reference in main class use the reset function in functions of main class? I can only do sth like
var myTimerObject:TimerCountDown = new TimerCountDown(timer, "seconds", 40, "0!", this);
but have no idea on calling reset function.

You can call it like this :
myTimerObject.reset();

You may keep a reference of myTimerObject in main class
public class Main {
private var _targetTimerObject:TimerCountDown;
public function set targetTimerObject(value:TimerCountDown):void {
_targetTimerObject = value;
}
public function someFunction():void {
if (_targetTimerObject) {
_targetTimerObject.reset();
}
}
}

Related

Flex - Problems in accessing static variable on another mxml page

First.mxml - Contains a Datefield control as follows:
<mx:DateField id="G2_CRTLoadDate" width="150" selectedDate="{modelProxy.G2_CRTLoadDate}" change="{modelProxy.G2_CRTLoadDate = event.currentTarget.selectedDate;changeManagerStatus()}"/>
I'm assigning this Datefield value to a static variable CERT_LOAD_DATE as follows(First.mxml):
[Bindable]
public static var CERT_LOAD_DATE:String = "";
private function changeManagerStatus():void
{
CERT_LOAD_DATE = G2_CRTLoadDate.selectedDate.toDateString();
}
Second.mxml -Here, I have a Combobox as follows:
<mx:ComboBox id="General_Release_Dates"
selectedItem="{modelProxy.General_Release_Dates}"
valueCommit="{model.General_Release_Dates = event.currentTarget.selectedItem;updateReleaseDate(event)}"
change="{model.General_Release_Dates = event.currentTarget.selectedItem;updateReleaseDate(event)}" close="closeHandler(event);" includeInLayout="true" visible="true">
</mx:ComboBox>
Inside the closeHandler function, I'm trying to access the variable CERT_LOAD_DATE as follows:
private function closeHandler(evt:DropdownEvent):void {
var CurrentDate:Date = new Date();
if(General_Release_Dates.selectedLabel.toString() == "TBD")
{
Alert.show(First.CERT_LOAD_DATE);
}
}
The alert box displays no value (null). Please help.
I can't figure out the relationship between First.mxml and Second.mxml from your question.
However, the following code can't access First.mxml.
Alert.show(First.CERT_LOAD_DATE);
Because the "First" is not the same instance as loaded "First.mxml".
How about to use singleton? It's accessible from anywhere.
1st, add MySingleton.as class like this.
package foo.bar
{
public class MySingleton
{
private var _cert_load_date:String;
public function MySingleton(internally:SingletonInternal)
{
super();
if(internally == null)
{
throw new Error("Please use getInstance() method.");
}
}
public static function getInstance():MySingleton
{
return SingletonInternal.instance;
}
public function set cert_load_date(value:String):void
{
_cert_load_date = value;
}
public function get cert_load_date():String
{
return _cert_load_date;
}
}
}
import foo.bar.MySingleton;
class SingletonInternal{
public static var instance:MySingleton
= new MySingleton(new SingletonInternal());
public function SingletonInternal(){}
}
How to use
Set value at First.mxml.
public var singleton: MySingleton = MySingleton.getInstance();
private function changeManagerStatus():void
{
singleton.cert_load_date = G2_CRTLoadDate.selectedDate.toDateString();
}
Second.mxml
public var singleton: MySingleton = MySingleton.getInstance();
private function closeHandler(evt:DropdownEvent):void {
var CurrentDate:Date = new Date();
if(General_Release_Dates.selectedLabel.toString() == "TBD")
{
Alert.show(singleton.cert_load_date);
}
}
Updated: Aug 27 10:00(JST)
I think there are two way to change First.mxml's element using singleton.
1) Binding the DateField value to singleton variables, and clear the value at Secend.mxml.
2) Assign to singleton variables whole "First", and control from Second.mxml.
I'll write here the 2nd way.
If you use this way, anything is controlable from Second.mxml.
MySingleton.as
private var _first:Object;
public function set first(value:Object):void
{
_first = value;
}
public function get first():Object
{
return _first;
}
First.mxml
singleton.first = this;
Second.mxml
public function something(): void{
First(singleton.first).G2_CRTLoadDate.selectedDate = null;
// The cast is unnecessary. Following code also works.
// singleton.first.G2_CRTLoadDate.selectedDate = null;
}
Also you can execute First.mxml's public function from Second.mxml.
singleton.first.someFunctionDefinedAtFirst();

Haxe: Return value of field

For some reason, I can't modify the value of a field in Haxe. Of course, this doesn't seem to be affecting all of my fields, just this one. Here's (what I'm pretty sure is) the applicable code. First, in the parent class:
class TopMenu extends Sprite
{
public function new()
{
super();
init();
}
private function init()
{
var tempField:BitmappedTextField = new BitmappedTextField( "File", 100, false );
trace( tempField.textWidth );
}
}
Then, in the child class:
class BitmappedTextField extends Sprite
{
private var _fieldText:String;
private var _fieldWidth:Int;
private var _addToStage:Bool;
public var textWidth:Int;
public function new( thisText:String, thisWidth:Int = 100, adTStg:Bool = true )
{
super();
_fieldText = thisText;
_fieldWidth = thisWidth;
_addToStage = adTStg;
textWidth = 55;
init();
}
public function init()
{
textWidth = 777;
}
}
I would expect the trace statement to return 777, but instead it will always return 55. In fact, no matter what I do, I can't seem to modify a field outside of the constructor class and then retrieve that value via the parent class. There's something horribly simple I must be missing, but I just can't figure it out. Maybe it has to do with the way Haxe uses getters and setters? Any help is appreciated, thank you.
I cant reproduce your problem however and you are missing a ; and a super call.
Try this code.
package;
import nme.display.Sprite;
import nme.display.MovieClip;
class HelloWorld extends MovieClip
{
public function new( )
{
super();
var tempField:BitmappedTextField = new BitmappedTextField();
trace( tempField.textWidth );
}
}
class BitmappedTextField extends Sprite
{
public var textWidth:Int;
public function new( )
{
super();
textWidth = 55;
init( );
}
public function init( )
{
textWidth = 777;
}
}

Action Script 3 Static Method

I'm new to Action-script OOP and i need to know how to chain methods like this example i have
I.$(button).bind('click',clickButton).bind('rollover',overButton).bind('rollout',outButton)
First i need to remove the I. to use dollar sign only like jQuery :) to select MovieClip and apply any action on it second issue that i have because this way i'm using static Methods Action-script restrict's me to use only static property saving the last one who called the action here is the class code to know what i mean:
package com.MAIN
{
import flash.display.Sprite;
import flash.events.MouseEvent;
public class I extends Sprite
{
private static var cSelector:Sprite;
public static function $(selector:Sprite)
{
cSelector = selector
return I;
}
public static function alpha(val:Number)
{
cSelector.alpha = val;
return I;
}
// bind mouse event to the element
public static function bind(EventStr,func:Function)
{
var func1:Function = function(e:MouseEvent){
func(cSelector);
}
// select the event from the list
if(typeof(EventStr) == 'string'){
// map the events in lowercase
var events:Object = {click:'CLICK',rollover:'ROLL_OVER',rollout:'ROLL_OUT',dblclick:'DOUBLE_CLICK',mousedown:'MOUSE_DOWN',mousemove:'MOUSE_MOVE',mouseout:'MOUSE_OUT',mouseover:'MOUSE_OVER',mouseup:'MOUSE_UP',mousewheel:'MOUSE_WHEEL'};
// check if the event exists in the list
if(events[EventStr] && MouseEvent[events[EventStr]]){
cSelector.addEventListener(MouseEvent[events[EventStr]],func1);
}
}else if(typeof(EventStr) == 'object'){
// add the event
cSelector.addEventListener(EventStr,func1);
}
return I;
}
public static function remove()
{
cSelector.parent.removeChild(cSelector);
return I;
}
}
}
Here you go, some steps in the right direction. However, this is a really, really, really crappy idea.
//$.as
package
{
import flash.display.DisplayObject;
//NOTE: there's NO class definition
public function $( selector : DisplayObject ) : IDisplayObject
{
//traverse displaylist to find <code>selector</code>
//and return an instance of IDisplayObject that holds the reference
}
}
//IDisplayObject.as
package
{
public interface IDisplayObject{
function alpha( value : Number ) : IBinding;
}
}
//IBinding.as
package jquery
{
public interface IBinding{
function bind( eventName : String, callback : Function, ...parameters ):void;
}
}
Once you've created concrete implementations of these you can do:
$( someMC ).alpha( .5 ).bind( 'click', function(){ trace( 'what a miraculously crappy idea !!!!' ) } );
You could try it like this:
interface Test {
function doBla(): Test
function moreBla(): Test
}
public class StaticTest {
private static const instance: Test = new InternalTest()
public static doBla() : Test {
return instance.doBla();
}
public static moreBla() : Test {
return instance.moreBla();
}
}
internal class InternalTest implements Test {
function doBla(): Test {
trace("bla");
return this;
}
function moreBla(): Test {
trace("more bla");
return this;
}
}

AS3: Type was not found or was not a compile-time constant

I'm having an issue with a little app I'm trying to create at the moment, it's my first try and dealing with classes but for some reason I can't create any instances of the class even if it's imported into the document. Here's the code for the class (named "Players"):
package
{
public class Player
{
public function Player(name_:String)
{
}
public var name_:String;
private var alignment:int;
public var healed:Boolean = false;
public var revealed:Boolean = false;
public var attacked:Boolean = false;
public var dead:Boolean = false;
public function action(target:Player)
{
}
public function describe():String
{
}
}
public class Citizen extends Player
{
public function Citizen(name_:String)
{
alignment = 1;
}
override public function action(target:Player)
{
}
override public function describe():String
{
return "Citizen";
}
}
public class Investigator extends Player
{
public function Investigator(name_:String)
{
alignment = 1;
}
override public function action(target:Player)
{
target.revealed = true;
}
override public function describe():String
{
return "Cop";
}
}
public class Doctor extends Player
{
public function Doctor(name_:String)
{
alignment = 1;
}
override public function action(target:Player)
{
target.healed = true;
}
override public function describe():String
{
return "Doctor";
}
}
public class Mafioso extends Player
{
public function Mafioso(name_:String)
{
alignment = -1;
}
override public function action(target:Player)
{
target.attacked = true;
}
override public function describe():String
{
return "Mafia";
}
}
}
And the code which creates the instance:
import Players;
stop();
var totalplayers:Number;
var playerArray:Array = new Array();
var playerType:Array = ["Citizen","Cop","Doctor","Mafia"];
var test:Citizen = new Citizen("James");
Both are in the same folder. I get the error code 1046 described in the title but I honestly have no idea why, flash picks it up in the code hints yet it comes up with that! Any help would be appreciated.
Also secondary question, I'll never initiate the Player class (except through inheritance with the other classes), so can I make it private?
Thanks
I'm assuming all that code is in a file called Players.as.
This is wrong. Each file should contain one class and the class should be the same name as the .as file.
You currently have two classes (Player and Citizen) within one file.
What you need to do is take the Player class you've defined and place it in its own .as. file with the same name (Player). Do the same for Citizen.
Then you can use:
import Player;
import Citizen;
Though this won't be necessary because you don't need to import classes that are in the same directory that you're trying to access it from.
As for the error, you're getting that because Flash is trying to find the class Players and you don't have a class with that name (just a file with that name).
Per your secondary question regarding whether ActionScript supports private classes, if you have a class that would not otherwise be accessed except internally by a public class you may define it as internal.
Internal classes are visible to references inside the current package.
If you do not want a class to be publicly visible outside a package, place the class inside a package and mark the class with the internal attribute. Alternatively, you can omit both the internal and public attributes, and the compiler automatically adds the internal attribute for you. You can also define a class to only be visible inside the source file in which it is defined. Place the class at the bottom of your source file, below the closing curly bracket of the package definition.
In the following example, both X and Y classes are defined in a single file (X.as). X may be referenced and instantiated as normal; however, Y is internal to X and only visible from from the scope of X.
package
{
import flash.display.Sprite;
public class X extends Sprite
{
public function X()
{
super();
var y:Y = new Y();
}
}
}
internal class Y
{
public function Y()
{
trace("internal Y ctor.");
}
}
This pattern is helpful when a class requires small data models that would not otherwise be accessed outside of a class.
Agree with others here should be as shown below (note filenames match class names, file names are denoted in brackets above code blocks). Also you wrote import Players instead of import Player, regardless as the other poster wrote if all classes are currently in the default package the import is unnecessary.
[Player.as]
package
{
public class Player
{
public function Player(name_:String)
{
}
public var name_:String;
private var alignment:int;
public var healed:Boolean = false;
public var revealed:Boolean = false;
public var attacked:Boolean = false;
public var dead:Boolean = false;
public function action(target:Player)
{
}
public function describe():String
{
}
}
}
[Citizen.as]
package
{
public class Citizen extends Player
{
public function Citizen(name_:String)
{
alignment = 1;
}
override public function action(target:Player)
{
}
override public function describe():String
{
return "Citizen";
}
}
}
[Investigator.as]
package
{
public class Investigator extends Player
{
public function Investigator(name_:String)
{
alignment = 1;
}
override public function action(target:Player)
{
target.revealed = true;
}
override public function describe():String
{
return "Cop";
}
}
}
[Doctor.as]
package
{
public class Doctor extends Player
{
public function Doctor(name_:String)
{
alignment = 1;
}
override public function action(target:Player)
{
target.healed = true;
}
override public function describe():String
{
return "Doctor";
}
}
}
[Mafioso.as]
package
{
public class Mafioso extends Player
{
public function Mafioso(name_:String)
{
alignment = -1;
}
override public function action(target:Player)
{
target.attacked = true;
}
override public function describe():String
{
return "Mafia";
}
}
}
It's unfortunate there's no abstract classes as this would be an ideal situation for an abstract class and abstract methods.

referencing variable in document class from another class

I need to increment an integer variable in a function within the document class upon transpiring event in another class. I can't seem to figure out how to call the function and reference the variable.
as3 newbie, please help!
The proper scope needs to be in place and the proper packaging.
Declare a static variable to handle your access to the Main Document Class
private static var _instance:Main;
public static function get instance():Main { return _instance; }
public function Main() { // constructor
_instance = this;
}
Declare some getters and setters in the Main Document Class
private var _foo:int = 0;
public function get foo():int{
return _foo;
}
public function set foo(value:int):void {
_foo= value;
}
And then in any class you need you can change to something as follows,
public class O {
public function O() {
Main.instance.set(Main.instance.get() + 1);
}
}
simple example, defining a variable 'test' in the document class:
package {
public class DocumentClass extends Sprite {
public static var test:Number = 3;
public function DocumentClass() {
test = 4;
}
}
}
now access the 'test' variable in another class:
package {
public class OtherClass extends Sprite {
public function OtherClass() {
DocumentClass.test = 5;
}
}
}
does this apply to your code?