as3 calling a function in Main.as Document Class from another class - actionscript-3

I am sure this is a popular question but I can't find the exact answer I need. I simply need to access a function or functions created in the Main.as document class. I have tried several methods and they do not seem to work. Here is one example I tried.
anotherClass.as // This needs to access functions Main.as
package com
{
import Main;
public class anotherClass
{
private var stageMain:Main;
public function anotherClass()
{
// tries to call a function in Main.as called languageLoaded. NO WORK!
stageMain.languageLoaded("English");
// in the Main.as languageLoaded is a public function
}
}
}

The cleaner way is to simply pass a reference to Main to the constructor of the class you want to be able to access it.
For example, your AnotherClass could look like this:
class AnotherClass
{
private var _main:Main;
public function AnotherClass(main:Main)
{
_main = main;
_main.test(); // Success!
}
}
And your main class:
class Main
{
public function Main()
{
var another:AnotherClass = new AnotherClass(this);
}
public function test():void
{
trace("Success!");
}
}

public class MainDoc extends MovieClip // as long as it extends eventDispatcher you re fine
{
private var otherClass:OtherClass;
public function MainDoc()
{
otherClass = new OtherClass();
otherClass.addEventListener("otherClassCustomEvent", onOtherClassReady);
otherClass.startLogic();
}
public function onOtherClassReady(event:Event = null)
{
trace("from other class:", otherClass.infoToShare) // traces "from other class: YOLO!"
}
}
public class OtherClass extends EventDispatcher // must extend the event dispatcher at least
{
public var infoToShare:String;
public function OtherClass()
{
}
public function startLogic()
{
// do what you got to do
// when you have your data ready
infoToShare = "YOLO!";
dispatchEvent("otherClassCustomEvent");
}
}
Once you're confortable with that, you can start looking into building custom events that could carry the variable to send back

Ok I got the following code to work. It's really a messy solution but I didn't know of a better way. It works. I just hope it's stable and does not use a lot of resources.
If you have a much better Idea I am open.
Here is the MainDoc.as
package {
import flash.display.MovieClip;
import flash.events.*;
import com.*;
import com.views.*;
import flash.display.*;
import flash.filesystem.*;
import com.greensock.*;
import com.greensock.easing.*;
import flash.system.System;
public class mainDoc extends MovieClip
{
/// (Get Main Doc flow) this creates an instace of the main timeline
/// and then I send it
private static var _instance:mainDoc;
public static function get instance():mainDoc { return _instance; }
/// Calls the defaultVars.as in to "vars".
var vars:defaultVars = new defaultVars();
public function mainDoc()
{
/// Makes this class ready to be passed to defautVars.as
_instance = this;
// Sends the _instance to defaulVars.as to be accessed later.
vars.getMainDoc(_instance);
// Calls a function in defaultVars.as and loads a var
vars.loadButtonVars("English");
}
}
}
Here is the defaultVars.as
package com {
import flash.display.Stage;
import flash.events.*
import flash.net.*;
import flash.display.*;
import flash.filesystem.*;
public class defaultVars
{
/// Makes the MainDoc.as a MovieClip
// Not sure if this is good but it works.
public var MainDoc:MovieClip;
public function defaultVars()
{
}
public function getMainDoc(_instance:MovieClip)
{
trace("CALLED" + _instance);
/// receives the _instance var and its converted to a MovieClip
// This can now be used in any function because I declared it a public var.
MainDoc = _instance;
}
public function loadButtonVars(Language:String)
{
myLoader.load(new URLRequest("Languages/" + Language + "/vars.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void
{
myXML = new XML(e.target.data);
/// Home Screen Buttons
homeT = myXML.Button.(#Title=="homeT");
homeB1 = myXML.Button.(#Title=="homeB1");
homeB2 = myXML.Button.(#Title=="homeB2");
homeB3 = myXML.Button.(#Title=="homeB3");
homeB4 = myXML.Button.(#Title=="homeB4");
homeB5 = myXML.Button.(#Title=="homeB5");
/// HERE IS WHERE I CALL FUNCTION from MainDoc after xml is loaded.
/////////////////
trace("xml loaded!!!! " + homeB1);
MainDoc.languageLoaded(Language);
}
}
}
}

Related

Actionscript 3 - Class Referring Errors

I a document class (Main) and a class connected to a symbol (MainMenu), and I get an error I just can't figure how to solve.. I get this error:
1136: Incorrect number of arguments. Expected 1.
it is reffering to "public var mainMenu = new MainMenu();" in my document class.
Anyways, here are my classes:
Main(document class):
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
public class Main extends MovieClip {
public var mainMenu = new MainMenu();
public function Main() {
// constructor code
startGame();
}
public function startGame(){
addChild(mainMenu);
}
public function initGame(event){
//Adding player and such..
}
}
}
MainMenu:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class MainMenu extends MovieClip {
private var logo = new Logo();
public function MainMenu(main:Main) {
// constructor code
mainMenu = new MainMenu(this);
logo.addEventListener(MouseEvent.CLICK, main.initGame);
placeButtons(event);
}
public function placeButtons(event:Event){
logo.addEventListener(MouseEvent.CLICK, initGame);
logo.x = - logo.width/2;
logo.y = 50;
addChild(logo);
trace ("MainMenu added");
}
}
}
Thanks
A few pointers...
Be mindful of your indentation.
Datatype your variables, arguments, and function returns.
Your MainMenu class was self instantiating itself (that's an infinite loop)
If you really need direct access to another classes function, consider making the child class extend the parent class. Alternatively, you could make the specific function a static function and call the function directly off the class without passing variable references. For example: Main.initGame()
Here are your classes, with a potential solution...
Main:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
public class Main extends MovieClip {
public var mainMenu:MainMenu;
public function Main() {
mainMenu = new MainMenu();
addChild(mainMenu);
}
public function initGame(e:Event):void {
//Adding player and such..
}
}
}
MainMenu:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class MainMenu extends MovieClip {
private var logo:Logo;
public function MainMenu() {
// Wait for it to be added to the parent.
logo = new Logo();
addChild(logo);
addEventListener(Event.ADDED_TO_STAGE, placeButton);
}
private function placeButton(e:Event):void {
// We only need this to happen once, so remove the listener
removeEventListener(Event.ADDED_TO_STAGE, placeButton);
// Now that we've formed the connection, we can reference the function dynamically
logo.addEventListener(MouseEvent.CLICK, this["parent"].initGame);
logo.x = - logo.width/2;
logo.y = 50;
}
}
}
I've left the structure as similar to your original intent as possible, but the above function reference is poor form. As a general rule, children should not have connections to their parents as it's a potential memory leak. You might instead add the event listener from your Main class.

Sharing variables in OOP AS3

In Main.as I have the following:
package {
import flash.display.MovieClip;
public class Main extends MovieClip {
public var damage:Number;
public function Main() {
// constructor code
var char:Character = new Character();
addChild(char);
}
}
}
And I have another package called Character.as
package {
import flash.display.MovieClip;
public class Character extends MovieClip{
public function Character() {
trace(damage);
}
}
}
I need to be able to share the damage set in the main.as with the character. Is there any way to make the speed more global?
Why don't you make damage a public property of your Character and then it'll be easily accessible via your Main class like this :
char.damage = 100;
trace (char.damage);
To do this, just add the property to your Character class like so :
public class Character extends MovieClip {
public var damage:Number;
public function Character() {
trace(damage);
}
}
But given your comment, I take it you would rather everything just be global and accessible everywhere as opposed to applying OOP concepts.
If so... just define it as a public static in your Main class like this :
public static var damage:Number;
and to access it anywhere you do this :
Main.damage = 100;
trace(Main.damage);
There is another way of sending values through packages (This way is not really sharing variables, but it could be useful for you). What this code does is that the class Character creates a variable, and this variables gets an value from the Main package:
Change the character.as to this:
package {
import flash.display.MovieClip;
public class Character extends MovieClip{
public function Character(a:int) {
//output will be the integer 10
trace(a);
}
}
}
and main.as to:
package {
import flash.display.MovieClip;
public class Main extends MovieClip {
private var damage:int = 10;
private var char:Character = new Character(damage);
public function Main() {
}
}
}
Edit: Not useful for realtime applications, because the values of private var damage will only be send on initialization of private var char:Character = new Character(damage).

Add other class as child in Flash Professional

Using Flash Professional CS5, I'm trying to add a child object in my script. I want to give the class which creates the child-object as parameter while creating. The problem is when I try to test the project, I get an error stating Incorrect number of arguments. 0 expected.
My MainClass.as:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class MainClass extends MovieClip {
var menuClass:MenuClass;
var gameClass:GameClass;
var highClass:HighscoreClass;
public function Main() {
this.StartOfProject();
}
public function StartOfProject() {
menuClass = new MenuClass(this);
this.addChild(menuClass);
highClass = new HighscoreClass();
}
And my MenuClass.as:
package {
public class MenuClass extends MovieClip {
var mainClass:MainClass;
public function Menu(mainClass:MainClass) {
this.mainClass = mainClass;
...
}
What am I doing wrong?
You named the constructor of your MenuClass incorrectly. It should be "MenuClass" not "Menu"
change:
public function Main() {
this.StartOfProject();
}
to:
public function MainClass() {
this.StartOfProject();
}
and:
public function Menu(mainClass:MainClass)
to: public function MenuClass (mainClass:MainClass)
and see if this already solves your problem

Is it possible to listen the event triggered by another class?

I've got 3 classes:
The class that recognizes the change in URL (using SWFAddress by Asual):
package swfaddress {
import flash.display.MovieClip;
import com.asual.swfaddress.*;
public class SwfAddress extends MovieClip {
private var dispatcher:Dispatch = new Dispatch;
public function SwfAddress():void {
SWFAddress.addEventListener(SWFAddressEvent.CHANGE, onChange);
}
private function onChange(e:SWFAddressEvent):void {
dispatcher.changed();
}
}
}
The class "Dispatch" that validates the URL and dispatching Event when finished
package swfaddress {
import flash.events.Event;
import flash.events.EventDispatcher;
public class Dispatch extends EventDispatcher {
public static const CHANGED:String = "changed";
public function changed ():void {
// some operations validating the URL
dispatchEvent(new Event(Dispatch.CHANGED));
}
}
}
Other class in other package that should receive info when the validation process has finished.
package menu {
import swfaddress.*
public class MenuPanel extends MovieClip {
var swfRead:Dispatch = new Dispatch;
public function MenuPanel():void {
swfRead.addEventListener(Dispatch.CHANGED, onChange);
}
private function onChange(e:Event):void {
trace("Hello World");
}
}
And the "Hello World" never appeared in the output window - so I'm not sure if it's possible that my MenuPanel has a chance to receive an info about completing the validation triggered by some other class?
You are creating two different instances of the dispatcher, and so the instance that is being called to validate your URL is not the same instance that you are listening to in the MenuPanel class.
A simple way around this would be to make the Dispatch class a singleton, so that only one instance of it exists and you can reference it from different points in your application. This works by giving the Dispatch class a static method that returns a self-contained instance of itself. You then call Dispatch.getInstance() whenever you want a reference to the class instead of using the new keyword.
Dispatch:
package swfaddress
{
import flash.events.Event;
import flash.events.EventDispatcher;
public class Dispatch extends EventDispatcher
{
// singleton instance
private static var _instance:Dispatch;
private static var _allowInstance:Boolean;
public static const CHANGED:String = "changed";
// get singleton instance of Dispatch
public static function getInstance():Dispatch
{
if (Dispatch._instance == null) {
Dispatch._allowInstance = true;
Dispatch._instance = new Dispatch();
Dispatch._allowInstance = false;
}
return Dispatch._instance;
}
public function Dispatch()
{
if (!Dispatch._allowInstance)
{
throw new Error("Error: Use Dispatch.getInstance() instead of the new keyword.");
}
}
public function changed():void {
//some operations validating the URL
dispatchEvent(new Event(Dispatch.CHANGED));
}
}
}
Getting a reference:
private var dispatcher:Dispatch = Dispatch.getInstance();

Need help understand MVC implementation within Actionscript 3 AS3, please

I am learning MVC implementation with ActionScript 3.0. So far, I have done alright but have couple of questions that can make this learning process very pleasant for me. I would highly appreciate your help and wisdom.
Let me explain how I am implementing a simple MVC implementation:
My Flash Movie is called FusionMVC. I have all the MVC files within the same package like this:
DataModel
DataControl
DataView
Application Facade
Here are my question:
As I understand it correctly, whenever I need to place a display object on the main stage, I declare or implement that display object in DataView class, am I right?
I have a symbol/display object called "Box" in the main library. I add this symbol to the stage by instantiating it within DataView class which I am able to see at runtime. Now if I need to add an EventListener called "ClickHandler" to this object:
Where do I declare this "ClickHandler" event, please? I am currently declaring it in the DataModel Class.
What I am confused about is to where to declare the EventHandler Methods. DataModel, or DataControl?
Thank you for your help. Here is the entire code:
//DATAMODEL
package
{
import flash.events.*;
import flash.errors.*;
public class DataModel extends EventDispatcher
{
public static const UPDATE:String = "modelUpdaed";
private var _txt:String;
public function DataModel()
{
}
public function get Text():String
{
return _txt;
}
public function set Text(p:String):void
{
_txt = p;
notifyObserver();
trace("MODEL HAS BEEN CHANGED");
}
public function notifyObserver():void
{
dispatchEvent(new Event(DataModel.UPDATE));
}
public function sayHello(e:Event):void
{
trace("HEY HELLO");
}
}
}
//DATACONTROL
package
{
import flash.display.*;
import flash.events.*;
import flash.errors.*;
public class DataControl
{
private var _model:DataModel;
public function DataControl(m:DataModel)
{
_model = m;
}
}
}
//DATAVIEW
package
{
import flash.display.*;
import flash.events.*;
import flash.errors.*;
public class DataView extends Sprite
{
private var _model:DataModel;
private var _control:DataControl;
public var b:Box;
public function DataView(m:DataModel, c:DataControl)
{
_model = m;
_control = c;
addBox();
}
public function addBox():void
{
b = new Box();
b.x = b.y = 150;
//b.addEventListener(MouseEvent.CLICK, vHandler);
addChild(b);
}
}
}
//APPLICATION FACADE
package
{
import flash.display.*;
import flash.events.*;
import flash.errors.*;
public class Main extends Sprite
{
private var _model:DataModel;
private var _control:DataControl;
private var _view:DataView;
public function Main()
{
_model = new DataModel();
_control = new DataControl(_model);
_view = new DataView(_model, _control);
addChild(_view);
}
}
}
You are correct - display objects should handle events from their own children:
public function addBox():void
{
b = new Box();
b.x = b.y = 150;
b.addEventListener(MouseEvent.CLICK, boxClickHandler);
addChild(b);
}
Handle the event in the view:
private function boxClickHandler(event:MouseEvent)
{
_control.sayHello();
}
And then you just need to add to your controller the method to change the model:
public class DataControl
{
....
public function sayHello():void
{
_model.sayHello();
}