Where can I define a class globally? - actionscript-3

I have a class, and I'd like to make it available for use anywhere within a Flash project. Where should I put it? Ideally, it'd be in a separate ActionScript file.

If your ActionScript 3 project using classes, you can simply create global variable using public static like this :
//MyClass.as
package {
public class MyClass {
public static var myValue = 3;
}
}
//Arbitrary.as
package {
public class Arbitrary {
function Arbitrary():void {
trace(MyClass.myValue); //3
}
}
}
You in every project, follow these steps to enable.
Click ActionScript 3.0 Settings...
Click Source path folder icon, select a you want src folders.

You can use top level default package declaration.
package com.abc.globals
{
//Note here No Class Declaration
public var globalVars:String = "Global is horrible";
}
So that you can use without import statement and you can use access variable without class or instance.
It is like our trace("Hello Global").
globalVars will access from anywhere in application.

Related

linking fla files together in actionscript using document classes

I am working in actionscript3, and since I'm self-taught, I think I've developed some bad habits, including coding on the timeline and using multiple scenes.
I am hoping to rectify this now that I'm working on a larger project.
Based on what I've read, linking multiple .fla files together is a better practice, each with their own document class. Is that correct?
If so, how do I load one .fla with its document class and then link that into the subsequent .fla file (instead of using scenes)? Or am I misinterpreting what was recommended?
Thanks!
There's no point to split your application in several loadable modules unless you have any of the following preconditions:
you have smart resource management to load and unload content
if you put everything into one file it gets just too big and hard to work with in design time or it takes far too long to compile
Regular AS3 alternative to working with scenes is creating/destroying content instances and using the main document class as their manager. You design content in the library and create behavior AS3 classes for them. Lets say, you have two content classes A and B. At the start the manager should show one of them and wait for the signal to show next one:
private var APage:A;
private var BPage:B;
gotoA();
function gotoA():void
{
if (BPage)
{
BPage.destroy();
removeChild(BPage);
BPage.removeEventListener(Event.CLOSE, gotoA);
}
APage = new A;
APage.addEventListener(Event.CLOSE, gotoB);
addChild(APage);
}
function gotoB():void
{
if (APage)
{
APage.destroy();
removeChild(APage);
APage.removeEventListener(Event.CLOSE, gotoB);
}
BPage = new B;
BPage.addEventListener(Event.CLOSE, gotoA);
addChild(BPage);
}
So, both A and B should have respective methods .destroy() that release used resources, unsubscribes methods from events, remove display objects, and so on, and they both should fire Event.CLOSE when they're done.
If you have many pages like that, you need to go for more algorithmic approach. For example, to create class BasicPage which will interact with manager and have the methods needed in all pages already declared:
package
{
import flash.display.Sprite;
class BasicPage extends Sprite
{
// A reference to the page manager instance.
public var Manager:PageManager;
public function destroy():void
{
while (numChildren > 0) removeChildAt(0);
Manager = null;
}
// Subclasses will have an access to this method to tell manager to show another page.
protected function showOtherPage(pageClass:Class):void
{
Manager.showPage(pageClass);
}
// A method that is called by manager when everything is ready.
// If page should take any actions on start it is a good idea to override this method.
public function startEngine():void
{
}
}
}
Then, example page A:
package
{
import flash.events.MouseEvent;
public class A extends BasicPage
{
// Lets say, class A in library have a designed button named Click.
public var Click:SimpleButton;
// We have things to undo here.
override public function destroy():void
{
Click.removeEventListener(MouseEvent.CLICK, onClick);
Click = null;
// Pass the destruction to superclass so it wraps its existence either.
super.destroy();
}
override public function startEngine():void
{
Click.addEventListener(MouseEvent.CLICK, onClick);
}
private function onClick(e:MouseEvent):void
{
// Lets use inherited method to show other page.
showOtherPage(B);
}
}
}
So, PageManager will be like:
package
{
public class PageManager extends Sprite
{
private var Page:BasicPage;
// constructor
function PageManager()
{
super();
showPage(A);
}
function showPage(pageClass:Class):void
{
if (Page)
{
Page.destroy();
removeChild(Page);
Page = null;
}
Page = new pageClass;
Page.Manager = this;
addChild(Page);
Page.startEngine();
}
}
}
This all could look scary at first, but it really isn't. PageManager will always have a current page, once there's a need to show another page, the current will be destroyed on a regular basis. Each page class will tend to its own content, which makes coding simpler, for you don't need to see the whole picture. If you need any persistent data, keep it in the PageManager so each page will have access to the data with no need for the pages to communicate with each other.

Can I still create Global variables in AS3

Following the answer here, I have created a file called MyGlobals.as and placed some global variables and functions so that I can access it from anywhere within my project just like AS3 buil-in functions such as trace() method.
This is MyGlobals.as which is located in the src folder (top level folder)
package {
public var MessageQueue:Array = new Array();
public var main:Main;
public var BOOKING_STATUS_DATA:Object;
public function postMessage(msg:Object):void {
MessageQueue.push(msg);
}
public function processMessage():void {
var msg:Object = MessageQueue.pop();
if (msg) {
switch (msg.type) {
}
}
}
Looks like my IDE (FD4) is also recognizing all these functions and variables and also highlighting the varibles and functions just like any other built-in global functions. However, I am getting compilation errors "Accessing possibly undefined variable xxx". The code is as simple as trace(MessageQueue) inside my Main (or another classe).
I am wondering if there was any change Adboe has done recently that it can't be done now or am I missing something? I am not sure if I need to give any special instructions to FD to include this MyGlobals.as?
I am using FD4, Flex SKD 3.1, FP12.0
I am aware of the best practices which suggests to avoid using this type of method for creating global variables but I really need it for my project for my comfort which I feel best way (right now) when compared to take any other path which involves daunting task of code refactoring. I just want do something which can be done in AS3 which I guess is not a hack.
I've done some playing around; it looks like you can only define one (1) property or method at package level per .as file. It must be the same name (case-sensitive) as the .as file it is contained in.
So no, nothing has changed since the older Flash Versions.
In your case that would mean you need five separate ActionScript files along the lines of:
MessageQueue.as:
package
{
public var MessageQueue:Array;
}
main.as:
package
{
public var main:Main;
}
...etc. As you can see this is very cumbersome, another downside to the many others when using this approach. I suggest using the singleton pattern in this scenario instead.
package{
public class Singleton{
private static var _instance:Singleton=null;
private var _score:Number=0;
public function Singleton(e:SingletonEnforcer){
trace(‘new instance of singleton created’);
}
public static function getInstance():Singleton{
if(_instance==null){
_instance=new Singleton(new SingletonEnforcer());
}
return _instance;
}
public function get score():Number{
return _score;
}
public function set score(newScore:Number):void{
_score=newScore;
}
}
}
then iin your any as3 class if you import the singleton class
import Singleton
thn where u need to update the global var_score
use for example
var s:Singleton=Singleton.getInstance();
s.score=50;
trace(s.score);
same thing to display the 50 from another class
var wawa:Singleton=Singleton.getInstance();
trace(wawa.score)

Global variables in action script 3

I'm new in action script 3. I intend to use global variable.
Here some way to do this and this
I download simple banner from here
Create file Globe.as in the same directory as test_banner_actionscript_3.fla. Globe.cs contains next code
package
{
public class Main
{
public static var myPencil:Number = 3;
}
}
banner code looks like this
mybanlink.addEventListener(MouseEvent.CLICK, mybanlinkClickListener);
function mybanlinkClickListener(e:MouseEvent):void {
trace(Main.myPencil); //3
var url:String="http://www.web-article.com.ua";
var urlRequest:URLRequest=new URLRequest(url);
navigateToURL(urlRequest);
}
but I get
error: 1120: Access of undefined property Main
Interesting that Intellisense suggests "myPencil" when typing "Main."
What's wrong?
You possibly forgot import Main in the begin of your banner code. Remember, when you use a class, always check that this class is imported.

Flex custom toggleswitch not working in actionscript

I have a custom Flex Toggleswitch component that changes the text values of the switch.
package skins
{
import spark.skins.mobile.ToggleSwitchSkin;
public class MyToggleSwitchSkin extends ToggleSwitchSkin
{
public function MyToggleSwitchSkin()
{
super();
selectedLabel="Serviceable";
unselectedLabel="Fault";
}
}
}
If I add the control using the MXML tag, it works fine. However, when I add the component using action script, it does not.
import skins.MyToggleSwitchSkin;
public function addToggle():void {
var myCustomToggle:MyToggleSwitchSkin = new MyToggleSwitchSkin();
hgroup.addElement(myCustomToggle);
}
The control dsiplays but will not activate.
Any ideas what I have missed?
Without seeing your MXML Code, it's tough to compare your two approaches, but I believe #al_Birdy addressed the problem. You've created a custom ToggleSwitchSkin; not a custom ToggleSwitch.
Modify your addToggle() method like this:
public function addToggle():void {
var myCustomToggle:MyToggleSwitch = new MyToggleSwitch();
myCustomToggle.setStyle('skinClass',skins.MyToggleSwitchSkin);
hgroup.addElement(myCustomToggle);
}
I suspect you'll have better luck.

Why i get this error

I have a png image on Library that i have declared it via Properties as Background class which extends BitmapData.
When i type:
var BMDClass:Class = getDefinitionByName( "Background" ) as Class;
i get: variable Background is not defined!!
But when i do:
trace( getQualifiedClassName( new Background(0,0) ) );
i get: Background !!
I can't figure out the cause of the error.
I believe this is because you need to have a reference to the Background class before you can actually get the definition by name. Simply importing the Background class will not compile the class in to your swf, you need to reference it in some way. Creating an instance of the class is one way, however you can also reference the class after your import.
try something like...
import com.somedomain.Background;
Background;
This should create a reference to you class and ensure it is compiled in to your swf.
Edit to show multiple class usage.
If you have multiple background classes, I would recommend trying to make them adhere to an interface. I would then also create a background factory class that would allow you to create background instances from your configuration file. This also means that you would be able to put all your references to your background classes in the factory class. Here is what the factory could look like.
// let the compiler know we need these background classes
import com.somedomain.backgrounds.*;
DarkBackground;
LightBackground;
ImageBackground;
class BackgroundFactory
{
public function create(type:String):Background
{
var bgClass:Class = getDefinitionByName(type) as Class;
return new bgClass();
}
}
Then to get a background instance from your config, you would do something like...
// parse your config file...not sure what format you've got it in.
// instantiate a background factory and create an instance based on the name from your config.
var bgFactory:BackgroundFactory = new BackgroundFactory();
var bg:Background = bgFactory.create(someStr);
Edit to extend example
package com.somedomain.background
{
interface Background
{
function get img():Bitmap;
}
}
package com.somedomain.background
{
class SomeImageBackground extends Sprite implements Background
{
protected var _img:Bitmap;
public function SomeImageBackground():void
{
_img = new SomeAssetFromLibrary();
}
public function get img():Bitmap
{
return _img;
}
}
}
Using these external classes would give you a bit more control over where the images come from. You could load them external, embed them using the embed meta data and even load them from the stage.