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








Scope Problem With An Object Within A Class


Hi folks,
i hope someone may help me out with this one:

i have a Class, let's say SomeClass:

PHP Code:



class SomeClass {
    var someObject:Object;
    var someString:String;
    
    function SomeClass() {
        someString = "i am the string that can not be reached 
from within 'someObject', why?";
        someObject = {
            scopeProblem: function() { trace("->"+someString+"<-"); }
        }
    }
    
    public function dynamicFunction(s:String) {
        someObject[s]();
    }







My aim is, to call a function with a string as parameter, which then calls that function in the Object, known from the string. That appears to be okay:


PHP Code:



import SomeClass;
var test:SomeClass = new SomeClass();
test.dynamicFunction("scopeProblem"); 




it traces "->undefined<-"

The thing is that the function is actually called, but it can neither reach a member var of that class, in this case "someString", nor a member method.

please help , or tell me about another method to gain succes =)

thanks in advance.




ActionScript.org Forums > ActionScript Forums Group > ActionScript 2.0
Posted on: 01-02-2007, 08:59 PM


View Complete Forum Thread with Replies

Sponsored Links:

Scope In Object Class File Using LoadVars - Help
Hi guys,

please help, i'm pulling my hair out!! i can't seem to get my head around scopes within a class file i've tried to create..

the aim of the class file is to go and retrieve a news article form a mysql database and store data such as "headline" and "textBody" etc in it so that i can then display it in a dynamic text box later in the movie file.

here is the code on the flash file creating the flash:

Code:

import as.*
trace("step 1");
var testING:newsArticle = new newsArticle(3);
trace ("step 2");
trace ("head = "+testING.headLine + " &id = "+testING.aID);
here is the actual class file newsArticle.as...

Code:
import mx.utils.Delegate;
class as.newsArticle {


var aID:Number;
var table:String = "sales_headlines";
var returnPage;
var graphic:String = "";
var headLine:String;
var bodyText:String = "";
var mainText:String = "";
var catID:Number = 0;
var displayAsNews:Number = 0;
var articleDate;

var $loader:LoadVars;
var $url:String = "http://www.xyz.com/flash/getdata.php";

var thisObj;

function newsArticle($id) {
//----------------------------------------------
// article is being created so go to the
// database and get all the details
//----------------------------------------------
aID = $id;
var thisObj:newsArticle;
_global.thisObj = this;
init();
execute();

trace ("sweet "+headLine);




} // end of constructor



function init () : Void {
$loader = new LoadVars();
$loader.onLoad = Delegate.create (this, onLoad2);
}
function execute () : Void {
$loader.load($url);
}
function onLoad2 (success:Boolean) : Void {
if(success) {

_global.thisObj.headLine = $loader.headline0;
trace ("ok ----- "+headLine);


} else {
trace ("bad !");
}
}

} // end of class file
and finally here is the trace output..

Code:

step 1
sweet undefined
step 2
head = undefined &id = 3
ok ----- The world's first 100Mbps Hotel Internet Pipe
Please can anyone advice on what the heck i'm doing wrong??? I want to be able to call "testING.headLine" anywhere in my movie file.. how do i make it a global object? and how do i populate the class variables so they can be accessed from the .fla file.... the aID works but not the headLine arrghhh!

Thanks in advance for any advice...

View Replies !    View Related
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!

View Replies !    View Related
XML Scope When Used In A Class
I'm building a event calendar, re-building in 2.0 actually. The first thing the constructor does is load an XML file. Then onLoad I fire off 3 functions. For some reason, nothing happens with an unqualified reference and I don't know what the scope of the function is.
This does not work.
code:
tempXML.onLoad = function(success){
trace("XML loaded!");
buildCalendar();
setDates();
leapYearCheck();
}


I don't understand why these both kinda work
code:
tempXML.onLoad = buildCalendar();//runs a trace and attachMovie within buildCalendar works


code:
tempXML.onLoad = buildCalendar;//runs a trace but attachMovie does not work

View Replies !    View Related
Class And Scope
G r e e t i n g s ~

If I use something like this in a seperate class.as file ...

//imagine a for loop here ...
this.attachMovie("d", "c"+i, depth);
this["c"+i]._x = xVar;
this["c"+i]._y = yVar;

I get nada in the movie. but ...

If I use the exact code on the timeline it works great. It seems I'm missing the point when using a seperate class file. On the timeline I'm declaring ...

import MyClass
myClass = new MyClass();



what do I need to do to get this to work from the class I'm bringing in ?

View Replies !    View Related
Scope In Class
if there is a way to reach to fRes function from fRelease() --> onRelease i need to know it.need any help.thanks.



private function fRelease() {
for (i=0; i<4; i++) {
eval("btn_"+i).onRelease = function() {
// it traces
// the go to fRes function
fRes();
};
}
}


private function fRes() {
// never came here
trace("damn");
}

View Replies !    View Related
Scope Within Class
I'm trying to do something I feel is pretty straight forward, but I keep running into problems.

I have a bunch of swfs that operate basically the same. They all have a row of buttons and depending on the button pressed an associated MC is displayed and the visibility of all the other MCs is set to false. I didn't want to build a component for this because each swf has a completely different look and style to it.

I figured it would be easy to create a TabSet class with a method where I pass in an array of references to all the buttons, and a similar array with references to all the MCs. That method would then set the onRelease event of each button to set the visibility of its associated MC to true and all others to false. Unfortunately when trying to set the onRelease even within a function in the class I keep running into errors dealing with scope because inside the event it can't access the original arrays that were passed in. I've tried using the Delegate.create method, but it seems to have the same limitations. I've included code below to show what I mean.


ActionScript Code:
import mx.utils.Delegate;
import mx.events.EventDispatcher;

class dhti.sc.TabSet{
   
        //Private Vars
    private var _btnArr:Array;
    private var _contentArr:Array;
   
        //Constructor
    function TabSet(){
        _btnArr         = new Array();
        _contentArr     = new Array();
    }
   
        //Setting the Tab Set
    function setTabSet(btnArr:Array, contentArr:Array):Void{
        _btnArr     = btnArr;
        _contentArr = contentArr;

        var i:Number = 0;

        for(i=0;i<_btnArr.length;i++){
           
            //Below are 3 ways of setting up the onRelease event
            //but none of them allow me to do what I need
           
                //Trying with a nested function
            _btnArr[i].onRelease = function(){
                //This will trigger the onRelease Event
                //but from in here you cannot access
                //_btnArr or _contentArr
            }
           
                //Trying Delegate setting the Scope to the Class
            _btnArr[i].onRelease = mx.utils.Delegate.create(this, buttonClicked);
               
                //Trying Delegate setting the Scope to the Button
            _btnArr[i].onRelease = mx.utils.Delegate.create(_btnArr[i], buttonClicked2);
        }
    }
   
   
    private function buttonClicked(){
        //This function is triggered with the button click
        //and it has access to _btnArr and _contentArr, but I
        //cannot determine which button was clicked
        //since "this" refers to the class
    }
   
    private function buttonClicked2(){
        //This function is triggered with the button click
        //but no access to _btnArr and _contentArr, but I
        //can determine which button was clicked
        //since "this" refers to the button itself
    }
}

View Replies !    View Related
Class Scope (again)
i thought i had this subject nailed and decided to re-write my code based on this new knowledge but for the life of me i cant see why this is not working.

i know it is a scope problem but i cant see it. The function loadXML does not work unless it is a static. I can't see why it needs to be static. myXML is declared ok, myXML is within the checkEntry function as is the onLoad etc. there is nothing wrong with the Delegate function - its SCOPE but i cant see the sucker - please put me out of my misery - i have looked at this for too long and put together so many different ways (which all work) but this just doesnt. thank you



PHP Code:



import mx.utils.Delegate
class XmlComponent
{
    var previousText:String;
    var keyListener:Object
    private var myXML:XML;
    static var controller;
    
    public function XmlComponent()
    {
        keyListener = new Object();
        controller = this;
        previousText = "";
        checkEntry();
    }
        
    private function checkEntry()
    {
        keyListener.onKeyDown = function(){    
            if((Selection.getFocus() == "_level0.controller.xmlInput_txt") and (Key.isDown(Key.ENTER)))
        {
            if(previousText != controller.xmlInput_txt.text)
            {
                myXML = new XML;
                myXML.ignoreWhite = true;
                myXML.onLoad = Delegate.create(controller,loadXML)
                myXML.load(controller.xmlInput_txt.text);
            }
            previousText = controller.xmlInput_txt.text;

        }
    }
            Key.addListener(keyListener);
    
    }
    
    //static function loadXML(success:Boolean):Void{
    function loadXML(success:Boolean):Void{
        if(success){
        trace("loadxml " + controller);
        }
    }
    
    public function tr() {
        trace(arguments.join(" : "));
    }
    
    


View Replies !    View Related
Class Scope
I just cant understand how can we retrieve the private variables of a class through other class. To explain in detail i ve 2 class files Person and Person2. Here is the code inside them.

Person.as class file

class Person {
private var fn:String;
private var ln:String;
function Person() {
fn = "myFirstName";
ln = "myLastName";
}
}



Person2.as class file

class Person2 {
private var root:MovieClip;
function Person2(mov) {
root = mov;
trace(root.pObj.fn);
}
}


The fla file that calls the class has this code on its first frame:

var pObj:Person=new Person()
trace(pObj.fn)
var p2:Person2=new Person2(this) //myFirstName


My question is how Person2 class can access Person class private variable.

View Replies !    View Related
Object Scope From MC
How can you call an Object method from an embedded MC onEnterFrame Event. Its another problem with scope that i cant figure out

Code:

function newTarget()
{
this.MyClip=attachMovie( "fly", "fly1",100);
this.MyClip.onEnterFrame=function()
{
//'this' here refers to the MyClip Instance, i need to target its object parent
this.Update()
}
}

newTarget.prototype.Update=function()
{
trace("called")
}

newClip=new newTarget()

I've tried various different solutions and cant get it to work. Any help or pointers appreciated.

Cheers

View Replies !    View Related
Object Scope Help
postObj = {};
postObj.me=this.postObj
postObj.page = 10;
postObj.lastPage=this.page/2
trace(postObj.lastpage)

how come it doesnt trace out the correct number. Is it got to do with scope? how do i solve this prob?

View Replies !    View Related
Get Scope Of Object
How is it possible for a Class to obtain the scope on which it was instantiated without passing a 'this' reference?

I need my Class to know whether it was instantiated on the root timeline or inside another MovieClip. Is this possible?

View Replies !    View Related
Custom Class Scope?
I created a custom class on the root of _level0.

Code:
FXML = function ()
{
...
}

FXML.prototype.getValue = function (xPath)
{
...
}
I want the scope of my class to be in all the movieclip.
I don't want to have to this:


Code:
var myfxml = new _level0.FXML()
How can my custom class have a global scope like others Flash objects?

View Replies !    View Related
Variable Scope In Class (AS 2.0)
I have a movie clip attached at runtime. I have a class linked to the movie clip. The movie clip is attached at root. All this works but check out how I am accessing the variables in the functions (ie: _parent.alphaon and _parent.alphaoff) Surely there must be a better way. Thanks for your comments.


Code:
//Constructor Function
function Screen() {
id = id;
path = _root["Screen"+id];
alphaon = 80;
alphaoff = 100;
setupdrag();
}

//Set Up Drag
function setupdrag() {

path.dragger.onPress = function() {
_parent.startDrag();
_parent._alpha = _parent.alphaon;
_parent.swapDepths(myDepth);
}

path.dragger.onRelease = function() {
stopDrag();
_parent._alpha = _parent.alphaoff;
}
}
}

View Replies !    View Related
AS 2.0 // Interval Scope In A Class
i have a function that i assign to an interval, after an amount of time it is to stop. problem is that interval is not able clear itself or access any properties in the class.

in the debug window it shows the function in the root of the class as i would expect but this. and _parent. have no effect.

class alpha
{
var myInterval;
var myNumber:Number

function myFunction()
{
trace(myNumber) // undefined
if(myNumber==20)
{
clearInterval(myInterval) // doesn't clear;
myNumber=0;
}else{
myNumber++;
}

function alpha()
{
myNumber=0
myInterval=setInterval(myFunction, 5000)
}

View Replies !    View Related
Math Class....available Everywhere? (scope)
I want to create a Class containing functions (similar to the Math class).
Also, like the Math class, I want it to be available everywhere.

For example, if I type
Code:
Math.floor(myNumber);
It works, no matter where I am in my code.

How can I make a class which has this ability?
I want to be able to type
Code:
MyMathClass.functionName();
and have it work, wherever I am in my code.

Is that possible??

Please help!
Cheers,
David

View Replies !    View Related
Help Xml Class Scope Issue
I am having a xml problem that is driving me crazy! I wrapped the the general methods for processing xml in a new class and the function that that is referenced by the onLoad handler loses the reference to the xml obj so I can't work with the xml obj. I did this so I can easily reuse this functionality.

In as the general method to process xml is create a new xml obj instance, set the onLoad to a function that will process the xml doc and set up all the business methods and then load an xml file into the xml obj. I wrapped these into a class for an app I'm working on.

The constuctor for the class sets my classes xmlObj instance variable to a new XML() obj. The loadXML(xmlfile) method sets up some variables and loads the file. The processXML() file is the method that is reference by the xml obj onLoad handler. But by the time the control enters this function the reference to my xmlObj is lost. It passes the if (success) confition meaning that the file was loaded successfully, but for some reason the my instances variable holding the xmlObj data is no longer an instance of XML type and is undefined.

PLEASE can somebody think about what might be causing this?

View Replies !    View Related
Variable Scope In Class
Hello,
I'm just getting started with OOP and writing classes. I've come across a problem. where Variables declared in the class are lost somewhere in the scope of things...

The static var X is'nt available to the method onBtn().. why? I'm probably missing something simple...


ActionScript Code:
class TestVars
{
    // reference to timeline
    var root:MovieClip; 
    // VARS
    var a:Number = 0;
    static var X:Number = 5;

    //constructor
    function TestVars(root:MovieClip)
    {
        this.root = root;
        init();
    }   
    // set up
    function init()
    {
        //  SET UP BUTTON 
        root.btnNext.scope = this;
        root.btnNext.onRelease = function()
        {
            this.scope.onBtn();
        }
       
        // START UP
        setVar(a);
    }
    //Set new variable 
    function setVar(t:Number)
    {
        a = t;
        trace('a: '+ a +' :'+ typeof(a))
    }   
           
       
    function onBtn()
    {
        trace('onBtn called: '+a+' + '+X+' = '+a+X) // TRACES: 0 + undefined = 0undefined   
        setVar(a + X);
    }
}

any help apreciated.
thanks

.henkedo

View Replies !    View Related
Scope In A Class Question
Hello, i'm new to OOP programming, and having trouble with scope within a class.

This class tweens an object, and at the end of the tween, i'm trying to use onMotionFinished to call another function in the class...

Can anyone tell me why it isn't working, and how it can?

Thank you

Mikey99

here's the code...
it works by passing the target movie clip to be tweened as the first parameter, then the speed of the tween.


Code:
import mx.transitions.Tween;
import mx.transitions.easing.*;

class TweenTest {
private var _endTween:Tween;
private var False:Boolean;


public function TweenTest() {}

public function startTween(target:MovieClip, speed:Number):Void {
new Tween(target, "_alpha", Regular.easeIn, 100, 0, speed, False);
new Tween(target, "_xscale", Regular.easeIn, 100, 60, speed, False);
new Tween(target, "_yscale", Regular.easeIn, 100, 60, speed, False);
_endTween = new Tween(target, "_rotation", Regular.easeIn, 0, Math.floor(Math.random()* 360 - 180), speed, False);


_endTween.onMotionFinished = function() {
trace("Has testFunction been called?");
testFunction();
}

}

private function testFunction():Void {
trace("Yes.. it has!");
}
}

View Replies !    View Related
Using Tween Class Changes Scope?
i have a custom class which implements the tween class. I'm just shrinking and enlarging a box.

when I just set the variables:
box_mc._width = boxOrigW;
box_mc._height = boxOrigH;

it changes the box to the correct size
but when i apply the same variables in the folling tween code, the size change is totally wrong

var boxSizerW:Object = new Tween(box_mc,"_xscale",mx.transitions.easing.None. easeNone,boxSmallW,boxOrigW,3,true);

var boxSizerH:Object = new Tween(box_mc,"_yscale",mx.transitions.easing.None. easeNone,boxSmallH,boxOrigH,3,true);

View Replies !    View Related
Class Variable Scope
I am trying to call an object's method in an event handler. It seems that the object was never defined.


Code:
// Main.as

class Main
{
var mc:MovieClip = null;
var b:Body = null;

static function main()
{
trace("main");

var m = new Main();
}

function Main()
{
trace("Main::Main");

this.mc = _root.createEmptyMovieClip("z00", 1);
this.b = new Body();

this.mc.onEnterFrame = this.onFrame;
}

function onFrame()
{
trace("Main::onFrame");
trace(this.b);
}
}

Code:
// Body.as

class Body
{
function Body()
{
trace("Body::Body");
}

function draw(mc:MovieClip)
{
trace("Body::draw");
}
}

Code:
// Output
main
Main::Main
Body::Body
Main::onFrame
undefined
Main::onFrame
undefined
Main::onFrame
undefined
...
Strangely, if I trace(this.mc) in Main::onFrame it is undefined also. The object that is generating the event is undefined?! I am going mad. Someone please help!

View Replies !    View Related
Scope Issue With Class
Hi,
It's been a while since I've posted, so hello everyone.

I've FINALLY got round to learing classes. Gawd knows how I've managed this far; I guess I like my functions laid out on the timeline too much!

Anyway... I've written a basic box class, then extended it a couple of times, making it more specialized each time.


Code:
Box // creates a movieclip, draws a box, sets it's color (optional)
DraggableBox // adds draggability
Draggable Square // makes sure the box is square, also adds color change on rollover
The last specialization is where I'm falling down with a scope issue. What I'm trying to do within an onRollOver handler is change the color of teh movieclip using my Box's setColor method.

However, the scope of the function now appears to be the movieclip, and I can't seemto reference the class anymore. I attempted to set an instance variable 'thisBox' in the head of the class that refers to the class instance, but I'm having no luck.

Bottom line is I can't seem to reference the class - so how do I do this?

Code snippet included below, and zip file attached. It's really very basic stuff, so thanks for your help if you choose to get involved.

Cheers,
Dave


Code:
class DraggableSquare extends DraggableBox {

private var thisBox:Box

function DraggableSquare(w:Number, h:Number, parent:MovieClip){
super(w,w,parent)

thisBox = this
trace('thisBox:' +thisBox)

setColor(0x999999) // SUCCESSFUL call to Box.setColor method
setDrag()
}

function setDrag(){

mc.onRollOver = function(){
trace('thisBox:' +thisBox)
thisBox.setColor(0xFF0000) // FAILED call to Box.setColor method
}

mc.onRollOut = function(){
thisBox.setColor(0x999999)
}

}

}

View Replies !    View Related
Scope Issue With Class Help
here's my code for my class...

it's used to make it easy to program keys to press in a game. and makes for smooth gameplay. Before this, i simply copy/pasted this code, and it has worked for awhile, but I want to make it a class to make my coding more organized.

anyway, here's the code...


Code:
class GamePlayControl extends Key
{
private var p_keyValues:Array;
private var p_externalFunction:Function;
private var p_updateRate:Number;

private var p_keysDownInterval:Number;
private var p_keysAreDown:Boolean;

private var p_keyListen:Object;

public function GamePlayControl(keyValues:Array, externalFunction:Function, updateRate:Number)
{
super();
trace("GamePlayControl instance created");
p_keyValues = keyValues;
p_externalFunction = externalFunction;
if (updateRate == undefined) updateRate = 30;
p_updateRate = updateRate;

p_keysAreDown = false;

p_keyListen = new Object;

trace("values initiated");

p_keyListen.onKeyDown = function()
{
trace("");
trace("KeyCode Pressed: "+getCode());
if (!p_keysAreDown)
{
trace("now check to see if any of the keys pressed are defined for gameplay");
if (pf_checkForKeysDown())
{
trace("the key pressed was defined");
p_keysDownInterval = setInterval(pf_runKeysDown, p_updateRate);
p_keysAreDown = true;
}
else trace("the key pressed was NOT defined");
}
}
addListener(p_keyListen);
trace("listener addded successfully");
}
private function pf_checkForKeysDown():Boolean
{
trace("checking for keys down");
var k:Number = p_keyValues.length;
for (var i:Number = 0; i<k; i++)
{
if (isDown(p_keyValues[i][1])) return true;
}
}
private function pf_runKeysDown():Void
{
trace("running 'pf_runKeysDown()'");
var k:Number = p_keyValues.length;
for (var i:Number = 0; i<k; i++)
{
if (isDown(p_keyValues[i][1])) p_externalFunction(p_keyValues[i][0]);
}
if (!pf_checkForKeysDown())
{
trace("keys no longer being pressed");
clearInterval(p_keysDownInterval)
p_keysAreDown = false;
}
}
}
everything works up until the key listener has to call the function 'pf_checkForKeysDown'

the problem is that it's not being called at all, because that trace never shows up... how can I make this work?

thanks for the help in advance.

oh yeah and you need to use this code in the FLA that uses the class...


Code:
var myKeyValues:Array = new Array();
myKeyValues[0] = ["left", 37];
myKeyValues[1] = ["right", 39];

var gpc:GamePlayControl = new GamePlayControl(myKeyValues, testFunc, 30);

function testFunc(val):Void
{
trace("testFunc()");
if (val == "left") trace("move left buddy");
if (val == "right") trace("move right buddy");
}
thank you!

View Replies !    View Related
Interval Scope Within A Class
Hello,
I'm trying to figure something out. Basically I am having trouble understanding the scoping of an interval when called from within a class. Here is an example I hacked up.


Code:
class TestClass {
var foo:String;
var i:Number;
var ID:Number;

public function TestClass() {
foo = 'bar';
i = 0;
ID = 0;
}

public function ShowFoo():Void {
trace("foo equals : "+foo);
if(i>5) clearInterval(ID);
}

public function IntervalFoo():Void {
var n:Number = 0;
trace('Please wait...');
ID = setInterval(ShowFoo,1000);
}
}
Why does IntervalFoo trace 'undefined' when calling ShowFoo directly reports the correct output? I boiled my bigger problem down to this example. I thinking solving this in my head will help me overcome the real issue.

Thanks for helping.
webg

View Replies !    View Related
Class Scope Question
Just a quick question, whats the correct way to access the "Stage" class in a diffrent class?

Example

ActionScript Code:
class classes.ScaleControl {
   
    function ScaleControl(){
        Stage.scaleMode = "noScale";
        Stage.align = "TL";
        Stage.showMenu = false;
       
        this.stageListener = new Object(); // not really sure this way works yet...
        this.stageListener.onResize = function(){
           this.doResize();
        };
        Stage.addListener(stageListener);
    }
}
/* [b]Output[/b] returns


**Error** D:ProjectsGovflashclassesScaleControl.as: Line 13: There is no property with the name 'stageListener'.
           this.stageListener = new Object();

**Error** D:ProjectsGovflashclassesScaleControl.as: Line 14: There is no property with the name 'stageListener'.
           this.stageListener.onResize = function(){

**Error** D:ProjectsGovflashclassesScaleControl.as: Line 17: There is no property with the name 'stageListener'.
           Stage.addListener(stageListener);

*/


For kicks I tried to access it via "_parent" and "_root" with no luck. I had assumed it was globaled by default. Do I need to global it somehow or is there a better way to access the other classes?

View Replies !    View Related
Scope In Actionscript Class
I'm having some problems with scope when trying to do some oop development within flash. Let's say I have a class that sends some params to a server and loads an xml snippet back, then traces out the xml value:

Code:
class printXML {
private var response_xml:XML = new XML();

public function printXML() {
var myloadVars:LoadVars = new LoadVars();
loadVars.ID = 12345;

response_xml.onLoad = function(success:Boolean) {
if(success) {
printValue();
}
}

nextAd_lv.sendAndLoad("http://myserver.com",response_xml,"POST");
}

private function printValue() {
trace(response_xml.firstChild.nodeValue);
}
}
The above code has a problem because within the response_xml.onLoad function, the printValue method doesn't exist. "this" refers to response_xml instead of the instance. I could maybe get around this by doing something like:

response_xml.onLoad = this.printValue;

but then I can't pass in the success boolean to see if the xml loaded properly. How can I keep my class in my scope when using handlers like onLoad within a class?

View Replies !    View Related
Scope Inside A Class AGAIN
Code:
private function mServerValidate() {
var xmlOUT:XML = new XML(schema00);
var xmlRTN:XML = new XML();
xmlRTN.ignoreWhite = true;
xmlRTN.onLoad = myOnLoad;
xmlOUT.sendAndLoad(this.path, xmlRTN);
//xmlOUT.sendAndLoad = Delegate.create(this, myOnLoad);
function myOnLoad(success:Boolean) {
var xmlpath = "/server/body";
var aTempXML = mx.xpath.XPathAPI.selectNodeList(this.firstChild, xmlpath);
trace(aTempXML[0].firstChild.attributes.success);
if (success) {
if (String(aTempXML[0].firstChild.attributes.success) == "1") {
trace("good login"+this);

//cant see this !!!!
im loosing scope after the "if (success) { " bit if i use delegate i cant pass the attributes i think.

??also can send it a ref to where it currently is..

View Replies !    View Related
Class Scope Within KeyListener
Hey everyone! First off this is my first post to this forum so if I miss some sort of forum etiquette please let me know and I apologize for the offense in advance.

On to my issue!

I have a class that puts things on the stage and will eventually make an object move on an isometric grid. The problem is I can't get a method to be called from another method in the same script with an onKeyDown function.

I understand when I try to call a method from a method that is in the same class the scope is on the movieclip or current object not the actual script. Using the delegate class is fine, but when I'm in the onKeyDown function that I have set up in one of my methods and try to use the delegate class it's like the scope has changed because it just ignores my method call. I found this here..http://www.actionscript.org/forums/a...3/t-98338.html

It seems like he's having the same problem but then the solution he posts doesn't make sense to me. I don't understand what he means in his last post on that thread by "changed the call to the keyListener"

Please help! This assignment is due in a week and my brain is about to explode!

Thank you in advance!

View Replies !    View Related
Scope In Tween Class
Hello all!

Can any one tell me why cant i control objects inside MovieClip play by tween class.

Thanks.

View Replies !    View Related
Class Scope And Events
Hi,

I've got a class that makes use of URLLoader with an event that fires when XML is loaded into my application. The event function however has no access to the class properties or functions. I would like to be able to access quizQuestions from within the event handler. What must I do?


Code:
public class QuizApp extends Sprite
{
//for managing questions:
private var quizQuestions:Array;

private function createQuestions()
{
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, showXML);
xmlLoader.load(new URLRequest("questions.xml"));
}

private function showXML(e:Event):void
{
XML.ignoreWhitespace = true;
var questions:XML = new XML(e.target.data);
var question:String;
var correct:Number;

for (var i:Number = 0; i < questions.question.length(); i++)
{
// Get question text.
question = questions.question[i].@title;
correct = 1;
var answers:Array = new Array();

for(var j:Number = 0; j < questions.question[i].answers.answer.length(); j++)
{
answers.push(questions.question[i].answers.answer[j].text());
}
}

quizQuestions.push(new QuizQuestion(question, 1, answers));
}
}

View Replies !    View Related
I Hate Class Scope
Why can't i access the Preloader and Container objects clips from my onMotionFinished function in my class?!


ActionScript Code:
/**
    Load Sub Stage class
    author: Ahmed I. Masri
    version: 1.1
    modified: 08/11/2008
    copyright: Ahmed I. Masri

    This code defines a custom class that loads the correct sub movie.
*/

// Import Built-In Classes
import mx.utils.Delegate;
import mx.transitions.Tween;
import mx.transitions.easing.*;

// Class to Load SubStages
class LoadSubStage {

    // Variable Definitions
    var Container:MovieClip;
    var StageLoader:MovieClipLoader;
    var Listener:Object;
    var Preloader:MovieClip;
   
    // Constructor Function to Select SubStage and prepare Stage
    public function LoadSubStage(linkToFile:String) {
        if (linkToFile != "intro_stage.swf") return;
        LIntroStage(linkToFile);
    }
   
    // Constructor Function to PreLoad and present Intro SubStage
    private function LIntroStage(linkToFile):Void {
        // Variable definitions
        StageLoader = new MovieClipLoader();
        Listener = new Object();
        StageLoader.addListener(Listener);

        // Empty Movie Clip to place Intro SubStage
        Container = _root.createEmptyMovieClip("MC_emptyHolder", _root.getNextHighestDepth());
        Container._x = 0;
        Container._y = 55;

        // Function to handle (pre)loading
        Listener.onLoadStart = Delegate.create(this, onLoadStart);
        Listener.onLoadProgress = Delegate.create(this, onLoadProgress);
        Listener.onLoadInit = Delegate.create(this, onLoadInit);
       
        Preloader = _root.attachMovie("MC_stageLoader", "MC_stageLoader" , _root.getNextHighestDepth(), {_x:400, _y:261.5});
        Preloader.MC_loadingProgressBar._width = 0;
        Preloader.txt_PercentLoaded.text = "00";
       
        // Loading of SubStage
        StageLoader.loadClip(linkToFile, Container);
    }
   
    // Function to handle start of (pre)loading
    private function onLoadStart() {
        Container._visible = false;
    }
   
    // Function to handle progress of (pre)loading
    private function onLoadProgress(mc:MovieClip, l:Number, t:Number):Void {
        Preloader.MC_loadingProgressBar._width = (l / t) * (Stage.width * 1.2);
        Preloader.txt_PercentLoaded.text = Math.round((l / t) * 100);
    }
   
    // Function to handle completion of (pre)loading
    private function onLoadInit():Void {
        // Variable definition
        var middleOrangeBarY:Number = _root.MC_headerBackground.MC_middleOrangeBar._y;
        var bottomOrangeBarY:Number = _root.MC_headerBackground.MC_bottomOrangeBar._y;
       
        // Fade out Preloader;
        var tweenPreloaderFade:Tween = new Tween(Preloader, "_alpha", Strong.easeOut, 100, 0, 10, false);
        var tweenMiddleBar:Tween = new Tween(_root.MC_headerBackground.MC_middleOrangeBar, "_y", Strong.easeOut, middleOrangeBarY, -3.5, 10, false);
        var tweenBottomBar:Tween = new Tween(_root.MC_headerBackground.MC_bottomOrangeBar, "_y", Strong.easeOut, bottomOrangeBarY, 619, 10, false);
       
        // On completion of Fade out
        tweenPreloaderFade.onMotionFinished = function() {
            Preloader.removeMovieClip();
            Container._visible = true;
        }
    }
}

View Replies !    View Related
Class Scope And GotoAndStop..
Hello,
I have a flash file with three labeled frames ("intro", "game" and "game_over"). And an .as file called Application.as. In the 2nd frame of the flash file ("game") I instantiate an instance of the Application class like so:


ActionScript Code:
var app:Application = new Application() ;
addChild( app ) ;

Within the Application.as file I invoke the function, gotoAndStop( "game_over" ) whenever the game has concluded. My problem is that the previously noted invocation doesn't transverse the main timeline to the "game_over" frame, instead, it does nothing. I'm assuming this is a problem of scope.

Here is the Application.as file, please note that I've omitted a great deal of code for simplicity:

Application.as

ActionScript Code:
package
{

   public class Application extends MovieClip
   {

      public function Application():void
      {

         gotoAndStop( "game_over" ) ;
      }

   }

}

View Replies !    View Related
Scope Of A Listener Within A Class
Here i am again.
I've wrote a class that manages the input from keyboard. It associates a button to an action and sends it to an object.
The problem appears at the key listener object.
At the constructor i define the variables of the class, but i can't access them from within the listener.

I've searched all this forum, found similar problems with no satisfactory answer. And the google didn't help too

How do i access these vars?







Attach Code

class KeyManager{

private var _UP:Object=new Object();

private var klisten:Object=new Object();

public function KeyManager(target:Corpo){
_UP.code=Key.UP;
_UP.action="UP";

trace(_UP.action) // returns "UP"

klisten.onKeyDown=function(){
trace(_UP.action) //returns "undefined"
}
Key.addListener(klisten);
}
}

View Replies !    View Related
Callback / Scope Within A Class
So this works when I move the function to call outside of the callback method onLoad, trace works inside the onLoad, so I know the function and the onLoad work fine. I was thinking it was a scope issue, but I followed ...

http://www.adobe.com/devnet/flash/articles/as_bestpractices_04.html

I think to a tee, unless I have something spelled wrong, or maybe I've just gone crazy? Your help is much appreciated.

HmcH







Attach Code

//in the var declare
var thisObj:ghost;

//in the constructor
var thisObj:ghost = this;

//the function with the scoping issue is called...
function addLinkDoc() {
toSend.Active = 1;
toSend.sendAndLoad("http://something.asp", toReceive, "post");
toReceive.onLoad = function(success:Boolean) {
if (success) {
thisObj.ENDit();
}
};
}

View Replies !    View Related
Class Variable Scope
Take a look at this code:


ActionScript Code:
import mx.utils.Delegate;class Test{  var secret:Number = 50;  function Test(mc:MovieClip)  {    var i:Number;    var new_mc:MovieClip;    for(i = 0; i < 5; i++)    {      new_mc = mc.attachMovie("my_movie", "new_name" + i, mc.getNextHighestDepth(), {_x: i * 50});      new_mc.i = i;      new_mc.onRelease = Delegate.create(this, alert);    }  }  function alert()  {    trace(this.i);    trace(this.secret);  }}


Well... Doesnt work at all... In the class, there isnt a instance of i, so, how may i access this property inside a class function? But i still have an way to access the class.

I could do this way:


ActionScript Code:
class Test{  function Test(mc:MovieClip)  {    var i:Number;    var new_mc:MovieClip;    for(i = 0; i < 5; i++)    {      new_mc = mc.attachMovie("my_movie", "new_name" + i, mc.getNextHighestDepth(), {_x: i * 50});      new_mc.i = i;      new_mc.class = this;      new_mc.onRelease = function()      {        trace(this.i);        this.class.alert();      }    }  }  function alert()  {    trace(this.secret);  }}


But this way, doesnt sounds good

Any suggests?

View Replies !    View Related
Class Variable Scope
I'm somewhat new to writing classes so forgive me if I get some wrong terminology.

I have a MC with a class attached to it, and I have other MCs within that MC. I need those MCs to be able to access variables within the main MC class. Here is a quick'n'dirty:


Code:
class Foo extends MovieClip{private var h:Number;
private var subMC:MovieClip;
function Foo(_h:Number){h = _h;
}

subMC.onEnterFrame = function(){trace(h);
}
}
How can I access variables in the Foo class from another MCs scope? I have tried using static var but aren't they constant regardless of instance?

View Replies !    View Related
Class Scope And Events
Hi,

I've got a class that makes use of URLLoader with an event that fires when XML is loaded into my application. The event function is a method of the class itself but it has no access to the class properties or functions.


Code:
private function createQuestions()
{
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, showXML);
xmlLoader.load(new URLRequest("questions.xml"));
}

private function showXML(e:Event):void
{
// Cannot access class properties and methods from here!
}
Are there any popular/common solutions to this problem?

View Replies !    View Related
Class Scope Loop
Hi

I have a base swf, which loops through xml, calling a page.as which pulls in seperate xml files and populates the pages.

I therefore need buttons to communicate back to thier respect page.as to do thier work...

atm I'm calling the pages via


Code:

var tempPage:Page = new Page(mc, i, 15, 155*i+100);
however unless I'm wrong I have to increment the tempPage variable so I can access the correct page.as

right? how do I do this?

thanks

View Replies !    View Related
I Cant Figure It Out Class And Scope AGAIN
Code:
class KeyTrap extends MovieClip
{
private var self:KeyTrap;
private var parent : MovieClip;
function KeyTrap (parent)
{
var self = this;
//constrctor
}
private function onEnterFrame ()
{
_root.debug.text = "fff";
trace ("looping");
self.onEnterFrame ();
};
}
SIMPLY WHY CANT I GET THE onEnterFrame working. Do I Have to have a graphic instance on the stage, im just using a single "new" object but cant get onEnterFrame to work.

thanks for any help

View Replies !    View Related
Function Scope In Class
In the 1st frame of my fla, i put 1 line:
var classScope:ClassScope = new ClassScope();


Code:
class ClassScope {
public var min:Number = 10;

function ClassScope() {
var keyListener:Object = new Object();
keyListener.onKeyDown = function () {
trace(min);
}

Key.addListener(keyListener);
}
}
But the trace result shows 'undefined'! How to get the 'min' value?

View Replies !    View Related
Scope Problem In Class
I am trying to have a some actions happen after onMotionFinished


ActionScript Code:
var subNavTween:Tween = new Tween(subNavContainer, "_alpha", Strong.easeOut, 0, 100, .5, true);
        subNavTween.onMotionFinished = function() {
            //trace(depth);
            var navArrow = subNavContainer._parent.attachMovie("navArrow_mc", "navArrow_mc", depth++);
            //trace(navArrow);
            var arrowTween:Tween = new Tween(navArrow, "_alpha", Strong.easeOut, 0, 100, 1, true);
            var arrowTween:Tween = new Tween(navArrow, "_y", Strong.easeOut, $target._y + $target._height + 5, $target._y + $target._height + 6, 2, true);
            navArrow._x = $target._x + ($target._width / 2);
        }


The problem is that depth is not accessible.

If this was just on a timeline i could do this

ActionScript Code:
subNavTween.classPath = this;

but the above class will reject that stating that

anyone know how i can reference the class path in that onMotionFinished function?

thanks

View Replies !    View Related
Object Scope Question
obPath=_root.pane.list.arrayTree[sIndex][rIndex];

i have a clip that requires quite a bit of data from a series of load var objects embedded in an array in another movie clip. i figured i could save a little typing for myself if i took the common part out and assign it to a var. the debug shows that obPath=[object #16 'LoadVars']

is this a reference to that object or has obPath become a complete copy of object # 16?

View Replies !    View Related
Super, Scope, Object
Having problems writing a class that includes the XML object via prototype.
I call the constructor for the XML via super(), but this overwrites any properties or methods in the child Object.Why?

The object is a manager for loading all data and SWFS etc.. into my site, thus requires extended properties and methods beyond the scope of the XML object alone.

Really annoyed as thought i had scope sorted but in my head but.......

the code is below ( any xml file to load will do)

SiteManager.prototype=new XML()


function SiteManager()
{
//if super() is commented out and you list variables on test movie this.textvariable has a value, however without it disappears and the Object doesnt inherit XML methods!!!!

super()
this.textVariable="i am a Value"
this.load("menus.xml")
this.onLoad=this.checkStatus
}
SiteManager.prototype.checkStatus=function(success )
{
if(success)
{
trace("done")
}else{
trace("failed")
}
}


webmanager=new SiteManager()



Hope someone can help me think my way through this.

Cheers

View Replies !    View Related
Scope Of Created Object
using this code to create 4 instances of the loader component and fill it with a jpg.

it works.. except none but the last instance created remains.

i would understand if i the instance names were the same (and with each iteration was being overwritten), but they are not.

so how to make the newly created instances permanent??


Code:
for (i=1;i<=4;i++)
{
vartmpLoader:mx.controls.Loader = _root.createObject("Loader", "loader" + i, 0);
tmpLoader.move(100*i,200);
tmpLoader.contentPath = "images_folio/folio_00" + i + ".jpg";
}

View Replies !    View Related
Shared Object Scope
Hi,

I am trying to find out how to allow multiple users on a Windows machine to all use the same shared object data.
What I need to be able to do is have data saved by one machine user visible by another machine user logged in to Windows under a different user account.
Here is an example of what I am trying to do:
User 1 logs in to Windows as User 1, runs a Flash Projector program from a CD that saves data to a shared object.
User 2 now logs in to Windows as User 2, runs the same Flash Projector program and is able to retrieve the data saved by User 1.
This seems like it should be a pretty basic requirement but I can't seem to get it to work.
Can anybody tell me what I need to do to get this to work?

I have tried using shortcuts from User 1 placed in User 2's Application Data path but this doesn't work.
I have tried Placing User 1's data in the "All Users" Application Data path also to no avail.

The shared objects are all saved in a directory named for the CD under the root for that user.

Any help in getting this working would be greatly appreciated.

Thanks,

Colin

View Replies !    View Related
Object Scope Question
Hello. I haven't asked for help in a long time so I'll get to the point.

I have:


Code:
MyPlayer = function()
{
this.n = 0;
};

_global.player1 = new MyPlayer();
in layer 1 of my movie.

later, in clip1 of layer 2 i have


Code:
onClipEvent(load)
{
_global.player1.n = 300;
trace(_global.player1.n);
}

onClipEvent(enterframe)
{
_global.player1.n += 3;
trace(_global.player1.n);
}
I am coding in flash mx, and when I run the movie it traces


Code:
300
303
3
3
3
3
I read the Variable scope tutorials and I understand most of it, but I dont know why _global.player1.n doesn't increase by 3 like I want it to?

thanks!

View Replies !    View Related
Arrays Within A Class? Can't Figure Out Scope.
I'm having the hardest time figuring out how Flash handles the scope of Arrays within a Class definition. If I define an integer, it can only be accessed by one instance of that Class. But if I define an Array, all instances access the same array.

here's my basic class:

Code:
class TestObject {
var myNumber;
var myArray=new Array();
}
and here's the FLA's use of that code:

Code:
stop();

test=new TestObject();
test2=new TestObject();

test.myNumber=50;
trace(test2.myNumber);
//returns "undefined", as it should

test.myArray[0]=4;
trace(test2.myArray[0]);
//returns 4, even though it shouldn't?
Does that make sense to anyone? Thanks for the help!

View Replies !    View Related
Lost Scope In A Class File
hi.

i've got a function that draws out a calendar for me. first it creates a movie clip and then a text field inside.
code:
// Create the Empty Movie Clip
_dateClipHolder = _root.createEmptyMovieClip("_dateClip"+j,_root.get NextHighestDepth());

// Create a Text Field Inside them
_dateClipHolder.createTextField("_thisDate"+j,j,0, 0,_columnWidth,_colHeight);

now in a totally separate function i want to access those text fields and set their properties -- like this:
code:
// I lose focus in this function
_dateClipHolder["_thisDate" + _today].border = true;
_dateClipHolder["_thisDate" + _today].borderColor = 0xFFFFFF;
_dateClipHolder["_thisDate" + _today].background = true;
_dateClipHolder["_thisDate" + _today].backgroundColor = 0xCCCCCC;

_dateClipHolder is a private class member. i think that i have to pass a reference back to the text field or something but i'm not sure how to do it. any ideas?? all help is greatly appreciated.

thanks. - fumeng

View Replies !    View Related
[AS2] Scope Of Class And Clearing Data
Hi :

I am using a class to create a random array of words.
In, for example, frame 30 I declare the class and create a new instance.

code:
import RandWord;
var Dummy:RandWord = new RandWord();
Dummy.Scramble
var Scrambled:Array = Dummy.ScrambledArray;


pseudo code
loop to add each word to 50 textfields
place a button on the stage to reset
reset button should reinitialise the class getting back a different order and then put those into the textfields.

At present the class works fine but on the reset button displays exactly the same as the first run.

If I re-enter this frame to re scramble the array how do I re declare the class or clean out the returned data.

TIA

View Replies !    View Related
Scope Or Path Issue In Class
Hello again!

I just watched an OOP video on gotoAndLearn the other day. I was messing with the idea, and I think I have a scope and/or path issue in my class. The class is very bare bones, so please don't laugh too hard.

ActionScript Code:
class Preloader extends MovieClip {
    var l:Number;
    var t:Number;
    var percent:Number;
    var preloader:MovieClip;
    var bar:MovieClip;
    //
    public function Preloader(url:String, level:MovieClip) {
        //
        var shell:MovieClip = level.createEmptyMovieClip("shell", level.getNextHighestDepth());
        var shell2:MovieClip = level.createEmptyMovieClip("shell2", level.getNextHighestDepth());
        shell.loadMovie(url);
        trace(level.preloader); // traces fine
        trace(typeof (level.preloader.bar)); //trace movieclip
        level.preloader._visible = false; // movieclip can be targeted here
        shell2.onEnterFrame = function() {
            l = shell.getBytesLoaded();
            t = shell.getBytesTotal();
            percent = (l/t)*100;
            if (t>4) {
                if (percent>0) {
                    level.preloader._visible = true; // can NOT taget clip here
                    level.preloader.bar._xscale = percent;
                }
                if (percent == 100 && shell._width>0) {
                    delete shell2.onEnterFrame;
                    shell.removeMovieClip();
                    shell2.removeMovieClip();
                    level.preloader._visible = false;
                    loadMovieNum(url, 0);
                }
            }
        };
    }
}
level.preloader._visible = true; // can NOT taget is where I have problem. I can traget the MC right away in the constructor but not here. Any ideas?

As always, Thanks

_Me.

View Replies !    View Related
OnFrameEnter Scope Issue In Class
I have a class file that does the following:
attach a clip to the stage
position the clip
run an onEnterFrame event to call another function every frame


After the enemy clip has been attached and positioned, the enemyBrain function is called. It runs an onEnterFrame event attached to the enemy clip. I can not seem to get the moveEnemy function to execute at all fom here. I am having a scope issue and I can't figure out what to do.

Code:
private function createEnemy():Void{
sEnemyDirection = "east"
mEnemyClip = mEnemyRoot.attachMovie(sEnemyMcAttach, sEnemyMcAttach, 1003);
mEnemyClip._x = nEnemyStartX
mEnemyClip._y = nEnemyStartY
enemyBrain()
}

private function enemyBrain():Void{
//moveEnemy()
mEnemyClip.onEnterFrame = function(){
trace("DO")
moveEnemy()
}
}

private function moveEnemy():Void{
trace("Enemy moving")
}

View Replies !    View Related
Setinterval Class Instance Scope
I have this class:


ActionScript Code:
class car extends MovieClip
{
    function car() {}
    // ...
    function bla() {}
}

Then I have my main class:

ActionScript Code:
class Main
{
    var aux:Car;

    function Main() {}
}

Now, I would want to access the bla() method from the car instance "aux" with a setInterval IN my Main class constructor. In other words I want to place a setInterval in the Main class constructor that has the target function argument my bla() method for the aux instance of Car ONLY.

What scope would I give it? Can I give somehow the car scope directly?
Don't know if it's relevant but my car class bla method isn't static and I want to access the bla() method for one instance only.

Hope this made sense

View Replies !    View Related
Copyright © 2005-08 www.BigResource.com, All rights reserved