Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    Flash




Variables From One Class To Another Class



lets say I have a variable being set on a class but i need that variable information to be passed on to another class. Is this possible?

thanks.



ActionScript.org Forums > ActionScript Forums Group > ActionScript 3.0
Posted on: 07-31-2008, 03:41 PM


View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread

[Flash 8] Referencing Class Variables From OnEnterFrame Created Within Class
Hi,
It's been a while since my last post here, but I was hoping someone could help me with a problem I'm having. I want to reference and change a class variable from within an onEnterframe function defined within a class. I can actually do this right now, but I want to do it in a different way. Here's a code sample of what I am talking about:


Test.fla file:

Code:
var t:tester = new tester()

Working tester.as file:


Code:
class tester{
private var num:Number = 100;

function tester(){
var classObj:tester = this;
var mc:MovieClip = _root.createEmptyMovieClip("test",1);
mc.onEnterFrame = function(){
trace(classObj.num); //This traces 100 (CORRECT!!!)
}
}
}
This traces 100 to the output window, just like it should

Here is the way that I would like to do it, because I want to reuse my onEnterFrame Stuff:

Code:
class tester{
private var num:Number = 100;

function tester(){
var classObj:tester = this;
var mc:MovieClip = _root.createEmptyMovieClip("test",1);
mc.onEnterFrame = this.mcOnEnterFrame;
}

private function mcOnEnterFrame(){
trace(num) //this traces undefined (BAD!!!)
}
}

As you can see, the work around to reading the class variable in the onEnterFrame function is to create a reference to the class object, before defining that function, then using the reference you created to access the class variables.

I have tried various iterations to get the second example working, but have had no luck. Does anyone know a way to get the second method working, or am I stuck using the first method.

Calling SetTimeout Within Custom Class And Cannot Access The Class' Variables
Hi All,

I'm creating an user interface with Flash 8, I'm new to Flash, my background is Java therefore I decided to use ActionScript to create a custom component that is reference within an external file.

My problem I believe is scope related. I have a status bar (label component), once I update the status bar I want to call the
"setTimeout" function to wait a couple of seconds before clearing my status bar. The "setTimeout" function is executing, but for some reason my status bar is not being cleared (accessed).

Below is a snippet of my code. Any help appreciated. Thanks.


/*
External File
*/
import mx.controls.Button;
import mx.controls.Label;

class MyApp
{
//private properties
private var mc_container:MovieClip;
private var btn:Button;
private var lbl_status:Label;
private var str:String = "do see me";

//constructor
public function MyApp(target:MovieClip)
{
trace("-- MyApp --");
mc_container = target.createEmptyMovieClip("mc_container", 100);
}
//public methods
public function init(width:Number, height: Number, xPos:Number, yPos:Number):Void
{
var my_app:MyApp = this;

btn = mc_container.createClassObject(Button, "btn", 1, {label:"click me"});
btn.setSize(100, 25);
btn.move(10, 10);
btn.clickHandler = function():Void
{
trace("btn clicked");
setTimeout(my_app.clearStatus, 2400);
//correct if I call directly
//my_app.clearStatus();
trace(str);
}

lbl_status = mc_container.createClassObject(Label, "lbl_status", 2, {text:"status bar message"});
lbl_status.setSize(200, 25);
lbl_status.move(0, 50);
}
public function clearStatus():Void
{
trace("calling clearStatus");
lbl_status.text = "";
}
}


/*
Called for Flash IDE
*/
var app:MyApp = new MyApp(this);
app.init(200, 200, 0, 0);

Class Getting Variables From Another Class
Hello guys, I have a problem. I'm new to classes and I began with this 2 stored in different .as files: (as3_main.as and as3_library.as)


Code:
// as3_main.as
package {
import flash.display.Sprite;
impor flash.utils.*;
import as3_library;
public class as3_main extends Sprite {
var library:Class = as3_library;
public function as3_demat():void {
trace(library.variable1); // undefined
trace(library.variable2); // undefined
trace(describeType(library));
}
}
}

Code:
// as3_library.as
package {
import flash.display.Sprite
public class as3_library extends Sprite {
public var variable1:String = "hey jude";
public var variable2:String = "dont make it bad, ";
public function as3_library() {
addtext("take a sad song");
}
function addtext(e:String):void {
variable2 += e;
}
}
}
The "trace(describeType(library))" shows that the instance exists and contains 2 different variables (variable1 and variable2) but the "trace(library.variable1)" and "trace(library.variable2)" always output "undefined"... what am I doing wrong?... I will appreciate any help...


Quote:




Extra information:
Both classes are the base class for 2 different .swf files (swf_main and swf_library) which have empty stages.
* swf_main is empty.
* swf_library has en empty stage but has 3 different symbols in the library checked as export for actionscript, export for runtime sharing and export in first frame; with the following names: symbol1, symbol2 and symbol3.

Getting A Class' Variables From Another Class
I need to access a variable that exists in class B from class A.

For example:

Code attached to frame 1:

Code:


import ClassA.as;
var Person = new ClassA();

Person.FirstName = "Franz";
Person.NoNeed.init("Ferdinand");



ClassA:

Code:


var FirstName:String;
var NoNeed = new ClassB();



ClassB:

Code:


var FullName:String;
public function init(Surname:String){
FullName = ClassA.FirstName + " " + Surname;
}



The problem lies at ClassB.init() - FullName = ClassA.FirstName + " " + Surname

How do I access ClassA.FirstName from ClassB.init()?
FullName = _parent.Person.FirstName + " " + Surname does not work.

Any ideas?

Calling A Function In Main Class From A Loaded Swfs Document Class
Hi
I have a main.swf that loads page.swf. They each have a document class called "Main" and "Page".

How can I call a function in Main from Page?

In AS2 this would be somthing like _parent.myFunction();


Cheers

Class Variables
hi all
In my class function each private member variable ,when changed affects the others in different instances of the same function. How do I stop this?

Class Variables
I have a class imported into another class.

Say for example:

package com.holderfolder {
import com.holderfolder.class1;
public class class2 extends MovieClip {
public function class2() {
//do stuff;
}
}
}

How would I call a variable declared in class2 inside of class1?

Thanks.

Class Variables
Hi to all.
I wrote a class and defined some variables in it.
But in enevt handler ( like loadVars.onLoad ) its variables is undefined.
Can any help me?
thanks a lot

Class Variables
Hi to all.
I wrote a class and defined some variables in it.
But in enevt handler ( like loadVars.onLoad ) its variables is undefined.
Can any help me?
thanks a lot

Class Variables
So I'm writing a Class in AS2 and I'm having problems in this one method. I have a method that uses a Tween class and I want to use the onMotionFinished method of the Tween class to change a class scope variable, but I seem to loose scope once I'm inside the onMotionFinished method. I'll attach the method code, but basically when I trace "this" inside the onMotionFinished, I get the Tween, and even tracing this.obj._parent doesn't give the class instance, it gives level that the tweened object was created on. "_state" is the class level variable I'm trying to change, but when I trace it from within onMotionFinished I get "undefined". Any suggestions to getting back to the class level?








Attach Code

public function show():Tween
{
new Tween(_mc.box,"_width",Strong.easeOut,_mc.box._width,100,16);
new Tween(_mc.box,"_height",Strong.easeOut,_mc.box._height,100,16);
new Tween(_mc.box,"_x",Strong.easeOut,_mc.box._x,0,16);
new Tween(_mc.box,"_y",Strong.easeOut,_mc.box._y,0,16);
new Tween(_mc.box.item_title,"_alpha",Strong.easeOut,_mc.box.item_title._alpha,100,16);
var unblur:Tween = new Tween(_mc,"blur",Strong.easeOut,4,0,16);
unblur.onMotionChanged = function()
{
this.obj.filters = [new BlurFilter(4,4,this.obj.blur)];
}
unblur.onMotionFinished = function()
{
_state = "shown";
}
return unblur;
}

Class Variables
I have created a new class called Line that extends the MovieClip class in a external .as file.

The class Line has a variable in it called XVal. (i used var XVal:Number; to declare)

I then created an instance of this using the line:
attachMovie("Line", 'line1', 100);

If i want to access the value of XVal from the instance line1 on the main timeline what syntax do i use?

cheers!

Dave

Need Some Help With Class Variables.
TypeError: Error #1009: Cannot access a property or method of a null object reference.

I have a class called Main, that extends MovieClip (it is dynamic) to house *my global* variables, functions etc.

This Main class, has a particular instance variable called tower_ind, I have created an instance of this class called main.

And using this right after: main.tower_ind = 5; trace(main.tower_ind); , appears to work perfectly.

But if I try to access this variable from another class which I create an instance of afterwards, I get the error mentioned at the top of this post.

I access it like this in the class:


Code:
var inst:String = "tower_basic1_" + this.root.main.tower_ind;
I have tried root, stage, parent, this.root, this.parent, this.stage etc etc, but no matter what, it still complains.....

Although in the future I may be converting to using a public static variable of my tower class to keep hold of the index (should piss this problem right off I hope), but I will still need to get this kind of result working for other things.

Variables In A Class
Hi there,
I had tried searching this for the last 2 hours =[ so I decided to give in and ask.

I am have a number of variables defined in my document class and I have noticed that if I were to call a function in the same class to edit the value of the variable, the change would only apply to the scope of the function.

Now I hope I used scope in the right context there =D

Here is my code to show what I mean:

ActionScript Code:
package {    import flash.display.*;    import flash.xml.*;    import flash.events.*;    import com.xml.xmlLoad;    import com.gui.mainGui;    public class main extends MovieClip {        private var _targetURL:String = "Musicinfo.xml";        private var getXMLLoad:xmlLoad;        private var getGui:mainGui;        public var xmlData:XML;        public var _lessonInfo:XMLList;         public function main() {            loadXML(_targetURL);            processXML();//This will return TypeError: Error #1009:                                //Cannot access a property or method of a null object reference.                                //at main/::processXML()            trace(xmlData);//This will also return an error similar to above        }        function loadXML(_targetURL) {            getXMLLoad = new xmlLoad(_targetURL);            getXMLLoad.addEventListener(Event.COMPLETE, onComplete);        }        function onComplete(evt:Event) {            xmlData = getXMLLoad.getXML();            trace(xmlData.fileInfo.blurb);//This traces the XML data            trace(xmlData.fileInfo.author);//And so does this        }        function processXML() {            trace(xmlData.fileInfo.blurb);//This dosen't =[        }    }}


Could someone explain why this is?
This may be a AS2 understanding but I thought that if I at changed the value of a variable made in the class, then the value would be the new value for every time the variable was called after the new value was put there.

Variables From The FLA To A AS Class
So I have this flash MP3 Player and Im passing a variable though the URL via JavaScript I can get it to Show the Variable in a text box but I need it to be used in an action script class thats in a separate .as file. Is this possible? Do you guys understand what I am asking.

For this to work I need to have the/a variable in my main fla file but needs to be used in the as class file.

Please Help.

Class Variables...
I'm having a difficult time trying to figure out class variables. The following should ouput "images/image.png" in the output window but it's saying null instead. To my understanding, the xmlLoaded function should set the private var theXML to the value of xml.... but it doesn't. This is how all of my books do it but it just isn't working for me. Is there something simple that I am doing all wrong? Please help, thanks!


In the first frame of my .fla:
Code:

import TheInfo;

var info:TheInfo = new TheInfo();
trace (info._theXML);


In TheInfo class:
Code:

package
{
   import flash.net.URLLoader;
   import flash.net.URLRequest;
   import flash.display.Loader;
   import flash.events.*;
   import flash.display.DisplayObject;
   
   public class TheInfo
   {
      private var _theXML:XML;;
      //var thePic:DisplayObject;
      
      public function TheInfo()
      {
         var xmlLoader:URLLoader = new URLLoader();
         var xmlReq:URLRequest = new URLRequest("info.xml");
         xmlLoader.load(xmlReq);
         xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
      }
      
      private function xmlLoaded(e:Event):void
      {
         var xml:XML= new XML(e.target.data);
         this._theXML = xml;
      }
   }
}


In info.xml:
Code:

<background>images/image.png</background>

Class Question: How To Access Timeline Objects From Class W/o Arguments
Hey all,

I am looking into builiding an application with OO functionality. I understand most of it. Except I cannot figure out how to access something in my app from a class. For instance, lets say I have one Loader class that loads some data and stores it in a variable inside the class (or on the main timeline, doesn't matter). Now, I know I can pass a reference to the data in an argument to another class for that class to manipulate. But if I have several data sources, and other variables and such, that I need to modify in a single class function, how would I do that without having to give the function access to them through arguments? I just want to be able to say, from a class, something like _root.someObject.someFunction();

So, any help would be greatly appreciated, and sorry if that made no sense at all, I tried to explain as best I could.

Happy Holidays!
Dave

AS3 Project In FDT + Flex SDK. Root Class Extends Visual Class From Swc
hello
question about compiling as3 project under FDT 3.0 with Flex SDK.

I want my main root class to contain some graphics already at the start. In Flash IDE I put some objects on the stage, make new symbol with all those objects inside, set linkage to MainClassGraphics, export it to swc, add this swc to source folder class-path. Then I write my root class:

Code:
package {

public class MainClass extends MainClassGraphics {
public function MainClass() {
trace('hey');
}
}
}

compiling with flex2 sdk - and I don't see any graphics. why?

if i try this way:

Code:
package {
import flash.display.Sprite;

public class MainClass extends Sprite {
public function MainClass() {
var s:Sprite = new MainClassGraphics();
addChild(s);
trace('hey');
}
}
}

then I see my graphics.. so swc looks like fine


crosspost here http://fdt.powerflasher.com/forum/vi...hp?f=21&t=2268

Accessing A Dynamic Text Field In A Class Other Than The Primary Class
I have tried to read and understand some of the other threads for this issue but, I think it would be easier to understand if I show my specific issue. I left some code out to make my issue more clear.

Alpha is the primary class with access to the stage. If I write the event listener and function contained in the Bravo function into the Alpha function it works. Although, I want it to be in a different class in the same package (such as the Bravo class).

I have created a instance of a class which is a physical object on the stage (lets say it's a card). The event listener is in the instance so that each instance has a self contained listener.

The bottom line is it works in the primary class but in no others. How can I make it access the text field (so when I click on the "card" the text field shows "something"?


ActionScript Code:
package a {
     public class Alpha {
          public function Alpha() {
               x:Bravo = new Bravo();
          }
     }
}

package a {
     public class Bravo {
          public function Bravo() {
               this.addEventListener(MouseEvent:CLICK, clickEvt);

               function clickEvt(event:MouseEvent) {
                    <MovieClip>.<MovieClip>.<DynamicTextField>.text = "something";
               }
          }
     }
}

ActionScript 2.0 Class Scripts May Only Define Class Or Interface Constructs.
This is driving me nuts. I have an old AS1 project which I upgraded to AS2. It uses an include file, settings.as, which has stuff like this:
settings = new Object();
settings.property = 'some value';

Then I include it on the main timeline like this:
#include "settings.as"

Every time I render, I get a million and one Compile Errors stating:
"ActionScript 2.0 class scripts may only define class or interface constructs."

But it isn't an ActionScript 2.0 class! It's just a regular include. How do I avoid the bogus Compile Errors?

AddChild Works With Document Class, But Not Timeline-instantiated Class
I cannot get a sprite to display for me when I create an instance of a very simple class in my FLA file's timeline.
However, when I make the class file the FLA's document class file, it displays just fine.
The task in question is simply drawing a square with the shape class.

Problem example:
My class, Test.as, resides in the same folder as my FLA file - so I don't use any import statement. I'm new to lots of CS3 stuff. Can anyone tell me why this doesn't work and create the shape on the stage? This seems to fail silently without any errors:
var myTest:Test = new Test();

Working example:
Setting the document class to Test.










Attach Code

// Test class

package {
import flash.display.*;

public class Test extends Sprite {

public function Test():void{
doThing();
}

private function doThing():void{
var myRect:Shape = new Shape();
myRect.graphics.lineStyle (2, 0xcc0000, 1);
myRect.graphics.beginFill(0xcccccc, 1);
myRect.graphics.drawRect(10, 10, 200, 200);
addChild(myRect);
}
}
}

[AS3] Making An Auto-generated Class Inherit From Custom Class?
hi, just wondering if this is possible

i was hoping to find a way to get a bunch of objects in my library to inherit from (or even be) one class that i have made, but without having to make .as files for every single one

is this possible, or is there any other way to give objects another classes functionality in an auto-generated class?

cheers

Tough One: Accessing Class Methodes From Other Class Files
Tough question for the experts...

In my classfile class Classes.tools.depthManager, I've got a static methode


Code:
public static function getLoopDepth():Number {
In another classfile Classes.tools.frameRateViewer, I want to access that methode


Code:
var tempDepth = Classes.tools.depthManager.getLoopDepth();
The compiler claims: "There is no class or package with the name 'Classes.tools.depthManager' found in package 'Classes.tools'."

So I tried writing import Classes.tools.* at the top of my Classes.tools.frameRateViewer.as, hoping I could just write


Code:
var tempDepth =depthManager.getLoopDepth();
But there the compiler claims: "The class being compiled, 'Classes.tools.depthManager', does not match the class that was imported, 'depthManager'."

I'm sure the Classes.tools.depthManager.as works fine: I can call the static depthManager.getLoopDepth() from a button in the fla file...

Any ideas? Thanks!

Window Class Attach Scrollbar/Pane Class?
I am using MX 2004 Prof...

Is there a way to attach a scrollbar/pane to the body of a Window class to make the content scroll?

Button Created Within Class Cannot Access Class Properties
Hi,
I'm using the following code within a class:
code:
_head_mc.attachMovie("headButton", "head_btn", this.getNextHighestDepth());

_head_mc.head_btn.onRelease = function () {
containingClip_mc._parent._parent.clickedHead(_per sonName);
}


The button gets attached (line 1). This works because I can see the mouse changing to a finger.

The onRelease function is declared and works. I know because if I put a trace in there, it works.

The function it calls (containingClip_mc._parent._parent.clickedHead also works, becuase I can see traces from within it.

But the _personName variable is passed as undefined.

I know that this variable has a value, because I can trace it outside the function, but it seems that this onRelease function is not able to see the variable. It's declared as private, but setting it to public doesn't fix anything.

I imagine there's something I don't understand about the scoping of variables. I've tried _parent references, but that doesn't appear to help either. Is there a better way to do this or a workaround?

Barrette

Added by edit
Okay, I've pretty much determined this is a scoping issue. From the onRelease function, I'm unable to access ANY of the functions within my class. I still would like advice on how to do so..

Barrette

[Flash8] Calling BitmapData Class From Within Custom Class
I've written a custom class which resides in a .as file. Is there any way that functions from within my class can call the BitmapData class for bitmap manipulation?

**Error** ActionScript 2.0 Class Scripts May Only Define Class........
**Error** ActionScript 2.0 class scripts may only define class or interface constructs.
b2.onPress = function() {

**Error** ActionScript 2.0 class scripts may only define class or interface constructs.
b3.onPress = function() {

**Error** ActionScript 2.0 class scripts may only define class or interface constructs.
b4.onPress = function() {

ok this is what i have.

1 Movie clip with links to a .as file all is working fine the above error occurs when i publish the 1 movie clip which is getting pulled into the main movie

Any idea's it does not happen when 1 movie clip is published on its own just when 1 move clip is pulled into my main movie clip.

[F8] Referencing A Static Class Inside Another Class's Instance
I've got a movie loading into a framework.

This framework has 1 instance of the class main called main.

Inside this class, another class is used, but it is used directly, not as an instance. E.g.:
code:
import com.StaticClass;
class main {
private function UseStaticClass():void {
StaticClass.init();
}
}


From my movie, I can reference the main instance as _root.main. Can I reference StaticClass at all if there's no explicit instance created or it's not assigned to a public variable?

I can't modify main to include getter/setter methods, that's why I ask.

Thanks.

Child Class Trigger Event For Parent Class
is there a way for a parent class to listen to a variable in a subclass, and when it changes, run a function?

This seems like a pretty simple thing to do. I'm trying to keep my subclass independent of my main class, so i just have a variable that is set to false, and when its finished, it sets the variable to true.

The only thing i can think of is having an onEnterFrame that keeps checking the variable...but it seems like an event would be more efficient.

thanks!

Tween Class Applied In Custom Class Not Working
var sizerW:Object = new Tween(pda_mc,"_xscale",mx.transitions.Tween.None.e aseNone,pdaOrigW,pdaSmallW,3,true);

this code produces and error when applied in a custom class but not in a fla?

the error = There is no property with the name 'None'.

Custom Transitionmanager Class Problem/class Scope?
I'm writing a class that fades from one scene to another in a video game. A custom transitionManager object is created, and a listener is attached. Once the fade out from one scene is complete, the listener is triggered, the scene switches, and the new scene fades in.

This is the error I'm getting: "There is no method with the name 'myTransitionManager'.
myTransitionManager.addEventListener("allTransitio nsOutDone", fadeListener);". It is given everytime myTransitionManager is accessed by any of the class functions.

I assume this is a class scope issue. How can I create a custom transitionManager object accessable to the entire class? I need it to be accessed by at least three separate class functions.

Here's the source, starting with the constructor for the GameSection class:


Code:
public function GameSection(clip_to_fade:MovieClip){
var myTransitionManager:TransitionManager = new TransitionManager();
}

//class methods

function switch_section(clip_to_fade:MovieClip, fade_in_scene:String) {
// Define a listener object to use with the Tween objects.
var fadeListener:Object = new Object();
//create event listener for transitions being complete
fadeListener.allTransitionsOutDone = function(eventObj:Object) {
trace("allTransitionsOutDone event occurred.");
gotoAndPlay(fade_in_scene);
fadeIn(clip_to_fade);
};
myTransitionManager.addEventListener("allTransitionsOutDone", fadeListener);


fadeOut(clip_to_fade);
}

function fadeIn(in_mc:MovieClip) {
myTransitionManager.start(in_mc, {type:Fade, direction:Transition.IN, duration:1, easing:None.easeNone});
}

function fadeOut(out_mc:MovieClip) {
myTransitionManager.start(out_mc, {type:Fade, direction:Transition.OUT, duration:1, easing:None.easeNone});
}


Thanks!

Static Class Variable Referencing Class Instance
I was given the task of writing a class that would send serial requests for xml data, the idea being that the requests could be added while previous requests were still in progress, but the class would queue them and wait for the reply of one request to come back before sending the next.

The way I did this was to create a class instance for each request, and the request itself would be stored in an instance variable, waiting to be sent. A static variable called queue (accessible to all instances) was then given a reference to the instance, and when this reference got to the top of the queue, queue would call the sendRequest() method on that instance.

The reason why I am using one instance per request is so that the replies can be retrieved via the instance, so keeping each request entirely discreet.

Everything works very nicely, but the problem is my IT manager looked at the code and told me that you cannot put a reference to a class instance in a class static variable... and for this reason he has informed my line manager that he has serious reservations about the code, and recommends that it is not incorporated it into the project. However, the code works very well on my local machine and on the testsite, and no-one has experienced any problems with it.

Can someone reassure me here... I can see absolutely nothing wrong with having a class static array hold references to each of the instantiated class instances. And the proof is in the pudding.. it works. Can anyone else see a problem here?

Why Is An Event On One Class Object Being Broadcast For All Instances Of That Class?
I have a custom class called McText which extends MovieClip, and includes an input text field. That class has a function to register itself as a listener to Key - Key.addListener(this). It does not register by default.

There are multiple instances of McText. But even though I only call the function to register on one of those instances, ALL of them fire an onKeyDown function when i type into their text field, regardless of whether i've registered that particular object to Key or not. I register one, I register them all.

This is a little annoying because I use this class everywhere, and I want to be able to assign an onKeyDown function for only one of them. At first i tried writing that function outside of the class itself, as in:
classObject.onKeyDown = function()
But that, perhaps unsurprisingly, created an onKeyDown function for every instance again.

I thought to myself "I know, I'll register McText with Key by default (in the constructor), write an McText.onKeyDown function in the class itself, and then get that function to use a broadcaster". The idea being that onKeyDown will fire on all of them, but the broadcaster will be registered to a specific listener on an object by object basis.

So I did that, and created a function to register a broadcaster listener. I then created a broadcaster listener in a seperate, different, class, throw it to the McText function so it registers with its broadcaster and guess what? Now that listener receives an event from every instance of that class.

There's no explicit use of static vars or functions anywhere.

Sorry for the long question, but can anyone enlighten me as to what's going on? You get virtual chocolate if you do

How Do You Listen In One Class For A Custom Event Dispatched From Another Class?
I am not sure how to word this, so here is what I would like to happen:

MyDocumentClass contains an instance of MyItem and MyItemManager. MyItem will fire an ItemEvent.ITEM_CHANGED event. I want MyItemManager to listen and react to that event. Possible? Here's my code:

ItemEvent.as:

ActionScript Code:
package
{
    import flash.events.Event;
   
    public class ItemEvent extends Event
    {

        public static const ITEM_EVENT:String = "itemEvent";
       
        public function ItemEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false)
        {
            super(type, true);
        }
       
        public override function clone():Event
        {
            return new ItemEvent(type);
        }
       
        public override function toString():String
        {
            return formatToString("ItemEvent", "type", "bubbles", "cancelable");
        }

    }
}

MyDocumentClass.as:

ActionScript Code:
package {
    import flash.display.Sprite;
    import MyItem;
    import MyItemManager;
   
    public class MyDocumentClass extends Sprite
    {
        public var item:MyItem;
        public var manager:MyItemManager;
       
        public function MyDocumentClass()
        {
            item = new MyItem();
            manager = new MyItemManager();
            item.dispatchCustomEvent();
        }

    }
}

MyItem.as:

ActionScript Code:
package
{
    import flash.display.Sprite;
    import flash.events.EventDispatcher;
    import ItemEvent;
   
    public class MyItem extends Sprite
    {
       
        public function MyItem()
        {
        }
       
        public function dispatchCustomEvent():void
        {
            dispatchEvent(new ItemEvent(ItemEvent.ITEM_EVENT));
        }
    }
}

MyItemManager.as:

ActionScript Code:
package
{
    import flash.display.Sprite;
    import ItemEvent;
    import flash.events.EventDispatcher;
   
    public class MyItemManager extends Sprite
    {
               
        public function MyItemManager()
        {
            addEventListener(ItemEvent.ITEM_EVENT, handleItemEvent);
        }
       
        public function handleItemEvent(e:ItemEvent):void
        {
            // do something here
        }
    }
}

Document Class Initialising Another Class With Display Objects
Hi

I'm currently learning AS3 and have got stuck with something fundamental to do with Flash and the Document Class.

I have a very simple Document Class as follows:

package {

import flash.display.*;
import com.Application;

public class EntryPoint extends Sprite {
public function EntryPoint() {
var app:Application = new Application();}}

}

I then would like to build out into other classes/patterns and want the following code to simply attach an item from the library on to the stage.

The item in the library has a Class reference of CircleTest and has a Base Class of flash.display.Sprite.

My Application class is as follows:

package com {

import flash.display.*;

public class Application extends Sprite{
public function Application() {
var mc_root:Sprite = new Sprite();

addChild(mc_root);

var circleTest:CircleTest = new CircleTest();

mc_root.addChild(circleTest);}}

}


When I compile this from Flash I get nothing other than an empty stage :-(

Please can someone tell me what I'm doing wrong here.

Many thanks in advance

D

How Do I Access A Variable Declared In My Document Class From Another Class
Hi there,

I'm pretty new to classes and am probably missing something really basic so apologies if this seems like a stupid question.

I'm trying to access a variable that I've declared in my document class from within another class.

I know I can pass the variable through when I call the class as follows:


Code:
var myBall:Ball = new Ball(5);
and pick this up in the Ball function within my Ball class as follows:


Code:
public function Ball(ballSpeed) {
trace(ballSpeed);
}
But what if I don't want to do that as I have a whole load of general global variables I want to access which were defined in my document class?

What I actually want to do is just have access to all the variables defined in the document class from within the Ball class.

I tried parent.variableName and various other ways of accessing what I need but all of them spit back errors.

Any help would be really appreciated - I'm sure this is very basic but I'm totally stuck on this.

Many thanks.
Ian

Applying A Custom Class To An Object In The Document Class...
How's it going guys. I just started learning Actionscript 3.0 and so far not bad. However, I'm having trouble applying custom created classes to objects in the main document class. I'm using Flash as the application, however there is no timeline scripting involved. I loaded the document class called Main.as:


ActionScript Code:
package
{
    import flash.display.MovieClip;
    import flash.net.URLRequest;
    import flash.display.Loader;
   
    public class Main extends MovieClip
    {
        private var _redBox:Loader = new Loader();
        private var _redBoxLink:URLRequest = new URLRequest("images/redbox.jpg");
        public var buttonScaleHover:ButtonScaleHover = new ButtonScaleHover();
       
        public function Main()
        {
            _redBox.x = 100;
            _redBox.y = 100;
            _redBox.load(_redBoxLink);
            addChild(_redBox);
        }
    }
}

Now, what I'm trying to do is apply this class named ButtonScaleHover.as to the _redBox in the document class. Here is the code for ButtonScaleHover:


ActionScript Code:
package
{
    import flash.display.Sprite;
    import flash.events.MouseEvent;
   
    public class ButtonScaleHover extends Sprite
    {
        private var _xScale:Number;
        private var _yScale:Number;
       
        public function ButtonScaleHover()
        {
            trace("The ButtonScaleHover Class is being loaded");
            _xScale = this.scaleX
            _yScale = this.scaleY
            this.addEventListener(MouseEvent.ROLL_OVER, onRollOver);
            this.addEventListener(MouseEvent.ROLL_OUT, onRollOut);
        }
       
        public function onRollOver(event:MouseEvent):void
        {
            this.scaleX *= 2;
            this.scaleY *= 2;
        }
       
        private function onRollOut(event:MouseEvent):void
        {
            this.scaleX = _xScale;
            this.scaleY = _yScale;
        }
    }
}

I tried using
ActionScript Code:
_redBox.ButtonScaleHover();
in the document class after i added it to the display object list. However, it didn't work. Basically, I'm just trying to apply a custom class to an object(in this case the loader). Thank you guys very much in advance.

Call Function Of Document Class From MovieClip Class
How can I run a function of the main document class from a class of a MovieClip? I usually just used MovieClip(parent).function(), but now my MovieClip has another parent. Or what do I have to pass to the MovieClip class when creating the MovieClip to acess the main document class?

Sharing Vars Between Document Class And An Imported Class.
I'm working on my first really in depth AS3 project, learning as I go.

I've been sorting through the XML docs and i've bumped my head into a bit of a question. So, to preface, I have been able to load the XML successfully, but I want to be able to use my own XML loader class to load the XML and then be able to reference it from the document class. Also, I'd like to be able to send a file path to the loader class when I call it.

Not sure if that makes sense, but I will post what I did and see how bad it is


The document class:

ActionScript Code:
package rg.sites{
   
    // flash classes
   
    import flash.display.MovieClip;
    import flash.display.Sprite;
    import flash.events.*;
    import flash.display.Graphics;
    import flash.display.Shape;
    import flash.text.*;
    import flash.utils.Timer;
    import flash.events.TimerEvent;
    import flash.net.*;
    import flash.errors.*;
   

    // RG classes
   
    import rg.classes.XMLSiteLoader;

    // Layout Objects

    public class SiteCurrent extends MovieClip {
       
        // vars
        public var siteLoader:XMLSiteLoader;
        public var site_xml:XML;
        public var xml_site_loading:String = "current_site.xml";
   
        public function SiteCurrent() {
            trace("Site Current is loaded");
            siteLoader = new XMLSiteLoader();
            siteLoader.addEventListener(Event.COMPLETE, xmlSiteLoaded);
        }//end constructor function
       
        private function xmlSiteLoaded(event:Event):void {
       
        trace(site_xml.toXMLString());
        trace("
" + "Background art: " + site_xml.section.(@id == "Splash"));
       
        }
       
       
    }//end class
}//end package

The XMLSiteLoader class:


ActionScript Code:
package rg.classes

//
// XMLSiteLoader version 0.1 beta
//

{
    //import fl.controls.*;
    import flash.net.*;
    import flash.events.*;
    import flash.errors.*;
   
    public class XMLSiteLoader extends EventDispatcher {
        //public var site_xml:XML;
       
        private var siteReq:URLRequest;
        private var siteLoader:URLLoader = new URLLoader();
        public var site_xml:XML;
        public var xml_to_load:String;
       
       
        public function XMLSiteLoader() {
            //trace(stage.xml_site_loading);
            if(xml_to_load == true) {
                trace("xml file path sent");
                siteReq = new URLRequest(xml_to_load);
               
            }
            else {
                trace("No XML file path sent, use default value");
                siteReq  = new URLRequest("current_site.xml");
            }
           
            trace("XML Site Loader is loading: " + siteReq);
            siteLoader.load(siteReq);
            siteLoader.addEventListener(Event.COMPLETE, xmlLoaded);
           
           
           
        } // constructor class
       
       
        private function xmlLoaded(event:Event):void {
        site_xml = new XML(siteLoader.data);
        trace("
" + "from XML Site Loader: " + site_xml.section.(@id == "Splash"));
        dispatchEvent(new Event(Event.COMPLETE));
        }
       
       
    }//end class
}//end package

I get an error that says:


Quote:




Site Current is loaded
No XML file path sent, use default value
XML Site Loader is loading: [object URLRequest]

from XML Site Loader: portfolios/splash_gallery/splash.xml
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at rg.sites::SiteCurrent/xmlSiteLoaded()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at rg.classes::XMLSiteLoader/xmlLoaded()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()




Thanks in advance for any thoughts or suggestions.
-g

Displaying A TextField From A Class That Is Called From My Document Class
I'm having a problem with my main project so I've made a small test project to replicate it. The code's included here.

I've created a new .fla called TextboxFromClass.fla that's empty except for a linked in Document class called TextboxFromClass.as

I've created another class called TextboxClass.as

Everything's linked and referenced properly - when I run it there's no errors and I get a trace output "Got here" but only the TextField for the Document Class displays ("From the Doc Class"), not the one from the TextboxClass ("From the TextBoxClass Class").

I'm guessing it's a scope thing but I'm fairly new to ActionScript 3.0 so I'd appreciate your help.







Attach Code

//Code in the Document Class (called TextboxFromClass.as

package script
{
import script.*
import flash.display.MovieClip;
import flash.text.*;

public class TextboxFromClass extends MovieClip
{
var inputNameLabel:TextField = new TextField();
var backgroundGreen : int = 0x2E510B;
var foregroundGreen : int = 0x00FF99;

public function TextboxFromClass()
{
with (inputNameLabel)
{
x = 300;
y = 200;
width = 200;
height = 30;
text = "From the Doc Class";
}
var format:TextFormat = new TextFormat();
with (format)
{
font = "Arial";
color = foregroundGreen;
size = 20;
}
inputNameLabel.setTextFormat(format);
addChild(inputNameLabel);

//This should output some text like the above - but doesn't
var abc:TextboxClass = new TextboxClass();
}
}
}

// Code in TextboxClass.as

package script{
import script.*;
import flash.display.MovieClip;
import flash.text.*;

public class TextboxClass extends MovieClip {
var t:TextField = new TextField();
var backgroundGreen : int = 0x2E510B;
var foregroundGreen : int = 0x00FF99;

public function TextboxClass() {
with (t) {
x = 300;
y = 250;
width = 300;
height = 30;
text = "From the TextBoxClass Class";
}
var format:TextFormat = new TextFormat();
with (format) {
font = "Arial";
color = foregroundGreen;
size = 20;
}
t.setTextFormat(format);
addChild(t);
trace("Got here");
}
}
}

























Edited: 02/09/2008 at 07:42:24 AM by SoCentral2

Tween Class In Custom Extend MovieClip Class
I want to use the tween prototype in a custom class that extends MovieClip. I am already including "lmc_tween.as" in my root and I have already replaced the "MovieClip.as" file in my flash directory with the one from the shared/Zigo directory. However, I still get compiler errors if I try to include "lmc_tween.as" in the class file, or without the include in the class it will compile but the tween prototype will not work in the custom class. Does anyone know how to fix this?

Checking To See If One Instance Of Class Hits Other Instances Of The Same Class?
Hi guys, the idea is similar to Yugop.com JAMPACK 01.

Let's say i have a bunch of balls/cells. I'm having trouble figuring out how to make it so that every other ball bounces off of every other ball.

so in short, it's really one instance being able to check all other instances of the same ball class?

any ideas guys and if you dont know what im talking about, please feel free to state that also.

Instantiating Character Class Inside Of Game Class
I am having a problem instantiating a Character class inside of a game class.

P.S. I am working on converting http://oos.moxiecode.com/tut_01/index.html these tutorials to A.S. 2.0.

Game:
ActionScript Code:
if ( i == charPos[1] && j == charPos[0] ) {
var char:Character = new Character();
char._x = (j*tileWidth)+tileWidth/2;
char._y = (i*tileHeight)+tileHeight/2;
}




Character:
ActionScript Code:
class classes.Character extends MovieClip {
function Character() {
var h = createEmptyMovieClip("holder", getNextHighestDepth());
var char = h.attachMovieClip("char", "char", getNextHighestDepth());
trace("new character created");
}
}

How Can A Child Class Pass Values To A Parent Class?
How can a child class pass values to a parent class?

Thanks to joshchernoff I've learned how to send events to a parent class and that works great. However I can't figure out how to pass values thru an event. Can anyone enlighten me?

Applying A Custom Class To An Object In The Document Class...
How's it going guys. I just started learning Actionscript 3.0 and so far not bad. However, I'm having trouble applying custom created classes to objects in the main document class. I'm using Flash as the application, however there is no timeline scripting involved. I loaded the document class called Main.as:

package
{
import flash.display.MovieClip;
import flash.net.URLRequest;
import flash.display.Loader;

public class Main extends MovieClip
{
private var _redBox:Loader = new Loader();
private var _redBoxLink:URLRequest = new URLRequest("images/redbox.jpg");
public var buttonScaleHover:ButtonScaleHover = new ButtonScaleHover();

public function Main()
{
_redBox.x = 100;
_redBox.y = 100;
_redBox.load(_redBoxLink);
addChild(_redBox);
}
}
}


Now, what I'm trying to do is apply this class named ButtonScaleHover.as to the _redBox in the document class. Here is the code for ButtonScaleHover:


package
{
import flash.display.Sprite;
import flash.events.MouseEvent;

public class ButtonScaleHover extends Sprite
{
private var _xScale:Number;
private var _yScale:Number;

public function ButtonScaleHover()
{
trace("The ButtonScaleHover Class is being loaded");
_xScale = this.scaleX
_yScale = this.scaleY
this.addEventListener(MouseEvent.ROLL_OVER, onRollOver);
this.addEventListener(MouseEvent.ROLL_OUT, onRollOut);
}

public function onRollOver(event:MouseEvent):void
{
this.scaleX *= 2;
this.scaleY *= 2;
}

private function onRollOut(event:MouseEvent):void
{
this.scaleX = _xScale;
this.scaleY = _yScale;
}
}
}


I tried using
_redBox.ButtonScaleHover();in the document class after i added it to the display object list. However, it didn't work. Basically, I'm just trying to apply a custom class to an object(in this case the loader). Thank you guys very much in advance.

Import Entire Class Directory Vs Specific Class
First off i've already tried searching for the answer with no luck.

Is there any benefit to only importing the specific classes you need as opposed to importing the entire class directory?

Example:
import flash.display.Loader;
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.display.Sprite;
import flash.display.BlendMode;
import flash.display.Bitmap;
import flash.display.BitmapData;
etc.....

vs
import flash.display.*;


Id like to clean up my code but not at the expense of performance....or does this just increase compile time?

Call Function In Parent Class From Child Class
Right, so I have a main Document class called Bundl where I'm loading all my other classes (navigation, portfolio, ...). What I'm trying to accomplish is to call a function inside my main Bundl class from a click from the navigation class.

The situation in code:
The Bundl Class (located in the root folder)

Code:
package {
import be.bundl.Navigation;

public class Bundl extends Sprite {
//vars called here

public function Bundl() {
nav=new Navigation("xml/navigation.xml");
addChild(nav);
}
//some more irrelevant functions here

//the function I need to call from the Navigation Class
public function portfolioXML(newXML:String):void {
portfolio=new Portfolio(newXML);
contentContainer.addChild(portfolio);
}
}
}
The code from Navigation class (located in /be/bundl)

Code:
//inside the btnClick function
var test:Bundl = new Bundl();
test.portfolioXML(_someVar)
Which results in an :
Error: Error #2136: The SWF file file:///Macintosh%20HD/Users/cerbellum/Projects/Bundl/site/FINAL/FULL.swf contains invalid data.at be.bundl::Navigation/btnClick()

I'm guessing this is due to the fact that I'm calling the parent class in a child or something like that, but how do I get this done otherwise? I must totally be overlooking something here.

Thanks in advance,
Kevin

CycleManager Class: Helper Class To Handle Events
Last edited by Codemonkey : 2007-01-24 at 10:55.
























I am just starting to get my feet wet with AS3 and thought I would post one of my first classes here for everyone to check out. While reading about Events in AS3 I noticed that one of the snippets of code I use most often as a Flash animator in AS2 is onEnterFrame functions. Seeing as how handling events takes a bit more legwork in AS3 and I would be typing the same stuff over and over to make something loop easily, I thought I would write this helper class to make it easier. I plan on adding to this but basically it allows you to add an onEnterFrame or Timer event as easily as this:


ActionScript Code:
_newManager = new CycleManager ();
_newCycle = _newManager.add (functionNameHere);

This would continue by default to just start an onEnterFrame loop and call the thrown function each time, etc. I know, I know, it's an easy class but hey I'm just getting started

Please see below for full classes and usage examples. Thank you!


ActionScript Code:
/*
    -------------------------------------
    DESCRIPTION:
    -------------------------------------
   
    Cycle Class that wraps both the TimerEvent.TIMER and Event.ENTER_FRAME classes
   
    -------------------------------------
    USAGE:
    -------------------------------------   
   
    function Cycle (action:Function, interval:Number = 0, begin:Boolean = true);       
   
    action: Function - the function that will be called each cycle
    interval: Number - the delay in milliseconds (if using the Timer class) (if this is
omitted the cycle defaults to frame-based) (defaults to 0)
    begin: Boolean - whether cycle should start immediately on init (defaults to true)
   
    -------------------------------------
    CREDITS:
    -------------------------------------
    Cycle Class by Ash Warren ([url]www.losthumans.com[/url])

*/
package
{
    import flash.utils.*;
    import flash.events.*;
    import flash.display.*;
   
    public class Cycle
    {
        private var _sprite:Sprite;
        private var _time:Timer;
        private var _action:Function;
        private var _isTimer:Boolean;
           
        public function Cycle (action:Function, interval:Number = 0, begin:Boolean = true)
        {
            _action = action;
           
            if (interval)
            {
                _time = new Timer (interval);
               
                _isTimer = true;
            }
            else
            {
                _sprite = new Sprite ();
               
                _isTimer = false;
            }
           
            if (begin)
            {
                start ();
            }
        }
       
        public function start ():void
        {
            if (_isTimer)
            {
                _time.addEventListener (TimerEvent.TIMER, cycleTimer);
                _time.start ();    
            }
            else
            {
                _sprite.addEventListener (Event.ENTER_FRAME, cycleFrame);            
            }
        }
       
        public function stop ():void
        {
            if (_isTimer)
            {
                _time.stop ();
                _time.removeEventListener (TimerEvent.TIMER, cycleTimer);
            }
            else
            {
                _sprite.removeEventListener (Event.ENTER_FRAME, cycleFrame);               
            }
        }
 
        private function cycleTimer (event:TimerEvent):void
        {
            _action ();
        }      
 
        private function cycleFrame (event:Event):void
        {
            _action ();
        }
    }
}



ActionScript Code:
/*
    -------------------------------------
    DESCRIPTION:
    -------------------------------------
   
    CycleManager Class that can control all aspects of a stack of Cycles for a Flash movie
   
    -------------------------------------
    USAGE:
    -------------------------------------   
   
    function add (action:Function, interval:Number = 0, begin:Boolean = true);   
   
    action: Function - the function that will be called each cycle
    interval: Number - the delay in milliseconds (if using the Timer class) (if this
is omitted the cycle defaults to frame-based) (defaults to 0)
    begin: Boolean - whether cycle should start immediately on init (defaults to true)
   
    returns: Number - the index of the added Cycle
   
    function remove (index:Number = -1);       
   
    index: Number - if left as default the manager will remove the last cycle added,
else it will remove the cycle at listed index value
   
    function start/stop (index:Number = -1);       
   
    index: Number - if left as default the manager will start/stop the last cycle added,
else it will start/stop the cycle at listed index value
   
    -------------------------------------
    CREDITS:
    -------------------------------------
    CycleManager Class by Ash Warren ([url]www.losthumans.com[/url])

*/
package
{
    import Cycle;
   
    public class CycleManager
    {
        private var _cycles:Array;
       
        public function CycleManager ()
        {
            _cycles = new Array ();
        }
       
        public function add (action:Function, interval:Number = 0, begin:Boolean = true):Number
        {
            return _cycles.push (new Cycle (action, interval, begin)) - 1;
        }
       
        public function remove (index:Number = -1):void
        {
            if (index >= _cycles.length || index < -1 || index == undefined)
            {
                return;
            }
            else if (index == -1)
            {
                var _c:Cycle = _cycles.pop ();
                _c.stop ();
                delete _c;
            }
            else
            {
                var _ca:Array = _cycles.splice(index, 1);
                _ca[0].stop ();
                delete _ca;
            }
        }
       
        public function start (index:Number = -1):void
        {
            if (index >= _cycles.length || index < -1 || index == undefined)
            {
                return;
            }
            else if (index == -1)
            {
                _cycles[_cycles.length - 1].start ();
            }
            else
            {
                _cycles[index].start ();
            }
        }
       
        public function stop (index:Number = -1):void
        {
            if (index >= _cycles.length || index < -1 || index == undefined)
            {
                return;
            }
            else if (index == -1)
            {
                _cycles[_cycles.length - 1].stop ();
            }
            else
            {
                _cycles[index].stop ();
            }
        }
       
        public function startAll ():void
        {
            for (var i:int = 0; i < _cycles.length; i++)
            {
                _cycles[i].start ();
            }
        }
       
        public function stopAll ():void
        {
            for (var i:int = 0; i < _cycles.length; i++)
            {
                _cycles[i].stop ();
            }
        }
       
        public function reset ():void
        {
            var _l:Number = _cycles.length;
           
            for (var i:int = 0; i < _l; i++)
            {
                var _c:Cycle = _cycles.pop ();
                _c.stop ();
                delete _c;
            }
        }
    }
}



ActionScript Code:
/*
    -------------------------------------
    USAGE EXAMPLE: CycleManager Class
    -------------------------------------
*/
package
{
    import flash.display.*;
    import CycleManager;
   
    public class Main extends Sprite
    {
        private var _test:CycleManager;
        private var _index:Number;
           
        public function Main ()
        {
            _test = new CycleManager ();
            _index = _test.add (test, 50);
        }
       
        public function test ():void
        {
            trace ("cycle loop");
           
            _test.stopAll ();
        }
    }
}

Variables On The Fly Inside A Class-how
If we need to declare all variables in a class like

var aR:Array;

for example , then how can i avoid the error message created when i try to dynamicly create a variable within that class...


this["c"+i]=i;
trace(this.c1);

error is that c1 has not been declared. This is very helpful to create these properties within the object then i can delete them later, i dont want to create a variable on the root.

thanks
mojito

Variables And Objects In Class
Hi,
I have 2 problems:
1.
class ClassA {
private var objects:Array;
function ClassA() {
objects = new Array();
// blah blah
}

public function reset() {
trace(objects);
}
}

I cannot reach "objects" array in reset() what is the problem here?

2. in this class I create objects with createClassObject() and movieclips
but I cannot remove them. What can I do for this?

thanx

Copyright © 2005-08 www.BigResource.com, All rights reserved