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




How To Have Constructor Wait For Xml To Load



How do I have a constructor wait until xml loads before finishing (so that if the class is instantiated the next line of code is useable with the xml). If I put a while loop in, that just stops the xml from loading and hangs the whole program.Attach Codeclass MyClass{ public var xmlDoc:XML; public function MyClass(){ functionWithXMLLoading(); /*Do something to stop function from finishing before xml loads */} private function callFunctionWithXMLLoading(){ /*function insides including xmlDoc.onLoad = function (success)....*/}}var item:MyClass = new MyClass();trace(item.xmlDoc); //I want this to be fully loaded(This is a basic overview of the functionality I want, not the exact code I'm using).



Adobe > ActionScript 1 and 2
Posted on: 05/12/2008 12:22:01 PM


View Complete Forum Thread with Replies

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

Does A Subclass's Constructor Automatically Call It's Superclass Constructor?
Hi guys

I have 2 classes:


Code:

class Player{

function Player()
{
super()
directionStack = new DirectionStacker()
}
}
and


Code:

class DirectionStack extends Player{

function DirectionStack()
{ }

}
does an infinite loop happen there? What I read in the Flash help (that comes with the software) is that you need to call super() if you want to call your superclass's constructor. But in this code, am I automatically going to the superclass's constructor? I'm getting this message:


Quote:




256 levels of recursion were exceeded in one action list.
This is probably an infinite loop.
Further execution of actions has been disabled in this movie.

Wait For Sometime And Load Another Swf?
Hi;

How can I load movies from outside and make them wait for 5 seconds and then goto next frame and load another external movie?

I will load these movies with buttons.

If anyone can help me I'll be happy...

Thanks

Load Random Mc.. Wait.. Then Load Following Mc
Last edited by [X]Silver : 2005-03-30 at 00:50.
























Is this possible?

I'm doing a flash site, that loads a random movie at startup;

ActionScript Code:
filename = ["test_0.swf", "test_1.swf",
"test_2.swf", "test_3.swf", "test_4.swf"];
path = "mc/";
i = filename.length;
k = Math.floor(Math.random()*i);
loadMovie(path+filename[k], movieTarget);


Is it then possible to assign a linked movie to each of the randomly loaded movies, and have it load after a 4 second wait?

Page loads -> random movie -> 4 sec wait -> Random movie unloads and is replaced by the movie in same category (linked)


Does this make sense?

Hope someone can help me...
thanks

Wait For An Image To Load
How can i wait for an image to be load with

lounge.loadMovie("images/" + imagepath);

The imagepath variable is returned from an XML string that is passed back from a database query. It seems as though if the XMl is still being generated the program doesn't wait for it to come through, continues processing and then generates an error.

Wait For Text To Load
I've created a movie clip within the _root of the file which gets the following text files...

loadVariables("home/welcome.txt", "_level2");
loadVariables("home/info.txt", "_level23");
loadVariables("home/actions.txt", "_level2");

on the main time line i've included this...

onClipEvent (data) {
_root.gotoAndStop(21);
}

When testing it, it doesn't seem to go to frame 21 on the main timeline, even though when i press "right click, forward" the text seems to have loaded.

I'm trying to create a movie clip that loads all the text from the txt files before it goes to the next frame.

Could anyone help?

Wait For The Page To Load First
Hey all!

Is there any way to have an swf wait to play until the HTML page it is embedded in loads completely? I have recently done a little home page animation for a friend's page. Unfortunately the background it quite heavy and my flash ends up loading first. I'd rather it not play until the HTML page has settled. Does anyone have a suggestion?

thanks -B

How To Wait For Variables To Load?
Seems to be simple, but I can't figure this out. I'm loading a list of resources from a text file using LoadVars(). The, I'm trying to use the data but it isn't loaded yet. What is the best way to wait? I have:

funtions Isloaded() {
// trace statements to show that mydata is loaded
}

mydata = new Loadvars();
mydata.onload = Isloaded();
mydata.load("data.txt");

// can't see mydata values here
functionthatneedsmydata();

// somewhere in here, the onload event occurs
// and I can see the data from Isloaded()

stop();


I tried putting this in various places:

do {
trace("loading...");
} while (not mydata.loaded);


But all I got was an endless loop. The data does get loaded, because in my 'onload' method I can see that the data is present. So, how do I wait and allow the data to load before continuing? I would assume that I would want something more deterministic than displaying a short movie or something to waste time - after all, I never know exactly how long this will take, right?

Thanks for helping!

Load Jpg, Wait 3sec. And Change Jpg
I am trying to make a slide show, that loads a picture and stay for 3 seconds and change picture. My question is if anyone know how to make it with action script.
Thanks

Load A .jpg But Wait For An Event To Display
Ok, I have my 2 buttons on my stage and a mc called placeHolder_mc into which the .jpgs are loaded. when a button is clicked the jpg is loaded and a function is called that gets the width of the pic. The frame around the pic adjusts to the size of the pic depending on it's width. I'm trying to get the frame to adjust first before the pic is displayed but I'm not sure how to make flash wait to display the jpg until after the frame is set. any ideas? here's my source code so far.

How To Preload And Then Wait To Load The Movie
I'm looking for a way to have a preloader with progress bar, and then once it gets to 100%, play a little in between movie and then load the movie that was preloaded. The problem is that the final movie has to load all over again like it's not in the cache. Is there any way to keep it in the background and call it up in that 3rd frame?

Thanks,
Brandon

Wait For Frames To Load In Steps
well after a fruitless and long search of threads here is my Q:

I have a single movie that contains 3 100k movies that i rotate thru using a setInterval call. I have a simple preloader on frame 1 and the movies on frame 10, 20 and 30. My preloader loads frame 10 and then goes to frame 10 to play the fisrt movie. On frame 10 i call the setInterval to move to frame 20 only if frame 20 has loader (otherwise stay on frame 10 which is fine). How can then make the setInterval call wait for frame 30 to be loaded if playhead has moved to frame 20? Seems simple but i cant seem to get it.. The code on frame 10 is:


ActionScript Code:
stop();
//
current = "movie1";
nInterval = setInterval(revolve, 33000);
//revolve movies//
function revolve():Void {
    if (_root._framesloaded>=20) {
        if (current == "movie1") {
            _root.gotoAndStop(20);
        } else if (current == "movie2") {
            _root.gotoAndStop(30);
        } else if (current == "movie3") {
            _root.gotoAndStop(10);
        }
    }else{
        //wait at the end of this frame until loaded//
    }
}

frame 20 and 30 have current = "movie1" etc to set the variable.

Any thoughts appreciated.

//

How Do I Wait For All The Sound Clips To Load?
Here is my issue. I have a function that is required to make a menu with the use of the duration of X number of sound clips (the number and soundclips themselves will change. I need to collect the duration of those soundclips dynamically and return those values to the initiating function to process them into a visual representation of the duration. My problem is that i don't know how to grab those values and return them back to the original function...


Code:
durationOfEachSound = loadAllAudio(audioFiles);

function loadAllAudio(audioFiles:Array){
for(var i = 0; i<audioFiles.length; i++){
var my_sound:Sound = new Sound();
my_sound.onLoad = function(success) {
if (success) {

}
my_sound.loadSound(audioFiles[i].path, false);
}
return soundDurationArray;
}
Any hints will be appreciated!

#include Wait Until Load Finishes
I have an #include issue.


I have several AS files that perform setup for my movies.  One loads variables, one sets styles, etc.
The problem is ActionScript doesn't wait for code to finish executing before moving on, specifically in the case of load().
So, #include "variables.as"  will run and move onto #include "styles.as" before variables.as has even loaded the txt file containing the variables I want to create.

How can I make it wait programmatically?


Currently I have an onLoad call to the next AS file. BUT I don't always us the same AS file and want them to run standalone.

I could create a frame that contains stop(); #include "variables.as" and has an onLoad function do a play();
then in the next frame have a stop(); and #include "styles.as".  This will most likely work... but it seems amaturish.

I want a programmatic solution, not a hard coded Timeline solution.

Can anyone help me out?

Thanks

Wait For Text File To Load....
I need Flash to load a text file to get variables.
The file loads on the first frame.
How can I make the movie stop until the file loads, then proceed after it has loaded?

Thanks.

Wait For Music To Load Then Play Timeline
I am trying to write some code so that the time will play once the sound file is loaded. I am doing this so the audio and video are in sync will they are playing online.

I have a button that loads the sound. and in the keyframe i have this code.
This is my first attempt on writing this kind of code. please let me know anyone can help. thanks

stop();
buttonLabel.autoSize = "left"
music.loadSound("audio/back1.mp3", false);

//------------button reads music.loadSound("audio/back2.mp3", true);


var BLoaded = music.getBytesLoaded();
var TotalB = music.getBytesTotal();
var precent:Number = Math.round((BLoaded/TotalB)*100)

playMusic = function() {
if (percent = 100) {
gotoAndPlay(nextFrame);
}
}


music.onLoad = function(success) {
if (success) {
(playMusic);
}
}

Making Frame Wait On Load Before Proceeding
This is a critical problem and I would GREATLY appreciate any leads!

In frame 1 of my Flash, I have the code below. Note the stop(); and play(); functions to wait for the XML to load before proceeding. When I run the SWF under Flash, it works fine.

But when I run the SWF within a web page or within a Windows page (using ActiveX control), it does not wait for the XML and just goes on and draws blank rows until the XML "catches up".

What's weird is that the next time around (if it does the gotoandplay() on the last frame), it DOES wait for the XML. But if it ends and then restarts, it blows right by the first time.

Please help!
Thanks,
Ron Cook

Help? Load Random Jpg Wait 100 Milliseconds Unload
how do I load a random jpg of say 100 jpgs have it appear for a fraction of a second then unload or go invisible?

Need Movie To Wait For Dynamic Variables To Load
I need to use the results of dynamic variables to choose whether or not a movie plays.  The problem is, it takes about 3-5 seconds for the variables to load from our database, and by then Flash is already done loading.

So I need it to

Start
Wait for dynamic variables to load
then continue processing whether or not movies play

I tried some OnClipEvent(data) stuff, but it didn't seen to work :(

My code it Frame 1 of Layer 1 is:
loadVariablesNum("http://www.sac-yolomvcd.com/flash/traps.asp", 0, "POST");    

And my code in the movie instance is:
onClipEvent (data) {
    stop();
    this.swapdepths(0);
    myvar = _root.daddy;
    if (myvar == "415"){
    this.nextFrame();        
    }
}
'daddy' is a dynamic variable loaded from the traps.asp (it's just a test)

Thanks for any help!

Help Preloader Doesn't Wait For Main Movie To Load
I am new at this and am having a time of preloading a main movie.

The preloader will run one time and then start the main movie. It doesn't allow the main movie to load before it starts to play it?

This is the script I used:
if _root.getBytesTotal()==_root.getBytesLoaded()
gotoAndPlay('Scene2',1)
else
gotoAndPlay(2)

The name of the main movie is "centraltruck" which would be Scene 2.

here is the url to the movie: http://www.trader-on-wheels.tv/centraliowatruck.htm

Please help!

MovieClip.onLoad - Wait For Movie To Load Before Progressing
Hi all,

I'm having trouble on loading text into my text area.

Sounds simple enough, however for certain dynamic purposes which I won't go into, I'm am loading in a separate .swf file with the text box into my main .swf.

I need to wait for the textField.swf file to fully load before I load the .txt file into it. However the detailsBodyHandler.onLoad = function(){} doesn't seem to wait for the loadMovie transaction, resulting in the .txt file to be immediately loaded, alas before the mainMovie.swf file has.

function loadText(pageNumber)
{
loadVarsText = new LoadVars();
loadVarsText.load("files/links/details/page"+pageNumber+".txt");
loadVarsText.onLoad = function(success)
{
tellTarget(detailsBodyHandler)
{
textInstance.text = this.textArea;
}
};
}

function populateBody(pageNumber)
{
if (pageNumber == 1)
{
// PROBLEM IS HERE
detailsBodyHandler.loadMovie("files/links/details/textField.swf");
// SHOULD WAIT FOR textField.swf TO LOAD BEFORE EXECUTING
detailsBodyHandler.onLoad = function()
{
loadText(pageNumber);
}
}

if (pageNumber == 2)
{
}

Thanks in advance,

Regards,

Justin

Making Preloader Wait For External Files To Load
Hi there, I've had a search around and can't find what I'm looking for, so I come to you guys in my hour of need (ok, not so melodramatic, but I'd appreciate some help )

Here's the site I'm working on www.savethebarrels.co.uk

Which has basically been put together from tutorials from here (thanks guys) and from experience and experimentation, the only real problem I'm having is that if the user is max'ing out their bandwidth, or is on a low bandwidth connection then when they click to go to one of the other sections, then sometimes the externally loaded txt file won't load in time, so the scrollbar goes squiffy, and also there is no text displayed until you click it again.

So my question is this: Is it possible to place into my preloader, something to make it wait for the external files to load, i'm not bothered about it contributing to the %age loaded, I just want to make sure it'll wait for them to load, so in pseudo code I'm looking for:


PHP Code:




this.loadVariables("news.txt?nocache=" + new Date().getTime);  
this.loadVariables("nands.txt?nocache=" + new Date().getTime);  
this.loadVariables("faq.txt?nocache=" + new Date().getTime);
if txt files loaded  
and if (_root.getBytesLoaded() == _root.getBytesTotalgetTime)  
then gotoandplay next scene







any help would be much appreciated, ta

Wait Script Or Wait On This Frame Required
hey,

i want my movie clip to stop and wait on a definied frame for a definied amount of seconds...
(...without adding the right number of "empty" frames after the key-frame...)

how can i script an easy funktion() to make my movie-clip wait for some seconds on a key-frame??

can somebody help me on this???
thanks

Actionscript To Load Random External Movie, Fade In, Wait, Fade Out, Repeat
Hello,
I'm trying to construct some AS3 that will load a random one of several external swf files, fade the instance in, wait 5 seconds, fade the instance out, and load a new random movie (it can be the same one; I don't want to get too complicated at this point).
I could do this with no problem using older methods, but the client insists this is written in 3.
Please help; I'm at my wits end!

How Do You "wait" For A Movie To Load Before Positioning
If I use this:
------------
loadmovienum("movie.swf", 1);
_level1._x=100;
_level1._y=150;
-------------
It loads but doesnt position.
If I loadmovienum in an earlier frame, like frame 9, and x-y position it in frame 10 using that code, it works.
BUT, Adding that to frame 9 causes other problems for me. So how do I wait for the movie to load before I position it, all in the same action script?

How Can I Make Frame 2 Wait Of Frame 1 To Load Data?
In frame 1, I'm loading data (pulling it from a URL in XML, parsing it, etc). It takes a few seconds and I want frame 2 to wait before doing it's thing because it needs the data first (otherwise it shows blanks).

How can I make frame 2 wait of frame 1 to load data?

Thanks in advance,
Ron

[MX04] Load Movie Clip...wait...load Another Movie Clip
ok...i'd like to do this all in actionscript if possible...on one frame.

one character (headshot). at timed intervals, the character would do something different...repeat.

[code]function antics() {
mc_Antics.start(0,0);
clearInterval(anticstime);
}
anticstime= setInterval(antics, 1000);

function antics2() {
mc_Antics2.start(0,0);
clearInterval(anticstime2);
}
anticstime2= setInterval(antics2, 2000);[code]

I don't know actionscript well at all, so is this just stupid? Any ideas on how to do this? It's not working right now...

[]'s Before Constructor
What does something like
ActionScript Code:
[Event(name="itemRollOut", type="fl.events.ListEvent")]
before the constructor mean?

Constructor Function
Another question:

I want to use on cunstructor function to build several objects but this does not seem possible?

function build(x, y) {
this["val"+x] = y;
}
//
this["testData"+1] = new build(1, 1);
this["testData"+1] = new build(2, 2);
//
trace("fk= "+this["testData"+1].val1);
trace("fk= "+this["testData"+1].val2);
//

I only get a result for the last trace

Any idea how I can get around this one?

Cheers

Main() Vs Constructor
Just out of curiosity really...

Why use a class method (i.e. public static main():Void ) to instantiate a class?

In Java, it's pretty obvious; you have to use main as it's the only function called automatically, so it's where you'd instantiate from.
But in Flash, why not just use the constructor? Either way it's something you invoke manually from the timeline.

As in either:
code:
public function ClassName ():Void {
//instantiate ivars, do other stuff...
};

or
code:
public static function main():Void {
//instantiate class, which then instantiates ivars and does other stuff...
var myInstance:ClassName = new ClassName();
};


Does it make any difference, except on a theoretically 'better practice' basis?

Problem Of Constructor
hello.
i have a problem of constructor

i wrote a class that extends the super class.
when i call the constructor of super class within sub class constructor that i don't konw between different
super(this, arguments)
and
super.constructor.apply(this, arguments)

and in my case ,it doesnt work if use super(this,arguments) ?_?

Constructor Problem
I made an "option" class and I am trying to create an instance of this class. A simplified class code is the following:

class Option
{

private var OPT_Name:String;

public function Option(N:String)
{

this.OPT_Name = N;

}

}


The Constructor i call in the main window is the following (again simplified):

var tempOpt = new Option("gwera");


The error i get when i try to compile is the following:

**Error** D:FlashAug 26 2005FunctionsXML_Functions.as: Line 136: Type mismatch.
var tempOpt = new Option("gwera");


Why is it calling a type mismatch, both are strings. If you can help me I would be very greatful. Also it is weird but when i submit any number instead of a string it lets it gives me no error. weird.

thanks

[OOP]constructor Function
I am trying to learn oop and i am confusing about how to build a constructor function.I mean, i dont understand scopes, what should i put in or out, or even IF i should put something in...
I mean, if i dont have any argument to the new class, so i dont need to put anything inside the constructor function, isnt it?
Thanks in advance

Constructor Not Being Called - Why?
Hi All,
I'm new to flash & Actionscript, but not new to scripting. I can't figure out for the life of me why this isn't working.

I'm workin on a Mapping system w/ GPS stuff. We're starting simple, we have a class representing a point, LatLonEle (lat/lon/elevation) and a Track which houses a lot of points.

The LatLonEle class is really simple as you can see ...
code:
class points.LatLonEle {
public var lat;
public var lon;
public var ele;

public function toString() {
return "Lat: " + lat + " Lon: " + lon + " Ele: " + ele;
}
}


Now the track class ... Again, nothing fancy.
code:
/**
Represents a track that will be drawn on the screen
Has a color and points
Points are probably loaded from a Yahoo formatted XML file
**/
import points.LatLonEle;

class tracks.Track {
//public static var totalTracks:Number = 0;
public var drawColor:String;
public var points:Array;

public function Track() {
//totalTracks++;
points = new Array();
drawColor = "0xaa4499";
}

/**
Return the start of the track
**/
public function getStart():LatLonEle {
return points[0];
}

/**
Return the end of the track
**/
public function getEnd():LatLonEle {
return points[points.length-1];
}

public function toString() {
return "Track has " + points.length + " points, starts at " + getStart();
}



And the test class. I'm using ASUnit for those that are curious ...
code:
import points.LatLonEle;
import tracks.Track;

class tracks.TrackTest extends com.asunit.framework.TestCase {
private var className:String = "tracks.TrackTest";
private var track:Track;
private var points:Array;


public function setUp():Void {
track = new Track();
points = track.points;

for(var i=0; i<10; i++) {
var point:LatLonEle = new LatLonEle();
trace(point);
point.lat = i+30;
point.lon = i+40;
point.ele = i+50;
points.push( point );
}

if(track.points.length != 10)
trace("we have a problem!");
}

public function tearDown():Void {
delete points;
delete track;
}

/**
Test to make sure that a track returns legit values
**/
public function testStartEndPoint():Void {
assertEquals("should be length 10", 10, track.points.length);

assertSame("Should be first point", points[0], track.getStart());
assertTrue("start should be a latlonele object", track.getStart() instanceof LatLonEle);

assertSame("Should be last point", points[10], track.getEnd());
assertTrue("end should be a latlonele object", track.getEnd() instanceof LatLonEle);
}
}

Basically the assertTrues in the testStartEndPoint fail, which is what prompted all the traces. So the trace in my for loop in setup() says that the new Point() is undefined. I don't understand how that could be so.


Code:
var point:LatLonEle = new LatLonEle();
trace(point);


That has got to be some of the simplest code ever. I have to be missing something glaringly obvious, but I don't know what it is. This is day 4 of my ActionScript experience, so hopefully it's something woefully easy.

Anyways, thanks for any help,
Jason

Constructor Functions
If you set up a link between a symbol and a class, how do you call the constructor function?

There are cases in my movie where I have a MC symbol already on the stage, but before anything happens in the movie, I need to gather information about the MC's children, and I need a constructor like function to do so.(My methods contain elements that arent defined in the class at compile time, but I cannot define them without first running a function to collect information about them)

There are also other times where I am dynamically creating instances of another type of MC,(different from above) and I need to pass information into the MC and also set it up as a Listener, but I do not know the parent of the calling function at compile time, and need to pass this MC the name of the parent calling function, and then register it as a listener.

I really dont want to hack this, and was wondering if anyone knows a clean way to do this. I am already knee deep in code, so multiple suggestions would be desired, just in case one suggestion wont work with the way I already have things running.

Thanks

AS3 Number Constructor Bug?
someone please tell me what the hell is going on here, the Number type is the only one that fails here:

in a new fla add these line:

Code:
var test2:Test2 = new Test2();
var test1:Test1 = new Test1();
Test1.as

Code:
package {

public class Test1 {

protected var var1:String;
protected var var2:Number;
protected var var3:int;
protected var var4:uint;
protected var var5:Boolean;

public function Test1(){

trace("TEST 1 CONSTRUCTOR", var1, var2, var3, var4, var5);
}
}
}
Test2.as

Code:
package {

public class Test2 extends Test1 {

public function Test2(){

var1 = "hello";
var2 = 10;
var3 = 5;
var4 = 15;
var5 = true;

trace("TEST 2 CONSTRUCTOR", var1, var2, var3, var4, var5);

super();
}
}
}
traces out:

TEST 2 CONSTRUCTOR hello 10 5 15 true
TEST 1 CONSTRUCTOR hello NaN 5 15 true
TEST 1 CONSTRUCTOR null NaN 0 0 false


????????

why is Number the only one coming back as NaN. And funnily enough its the number type I need, figures.

Variable Constructor
Hi,

I don't know how to say this, but I need to make a variable construction to shorten my code and was wondering if that was possible. I tried doing this:

var number:Number = (sum number here...)
var newHead:MovieClip = new ["Head_"+number];

and it won't work out. So is there any way to process this so I can actually create a reference to an increasing number?

Thanks in advance, Sid1120

[F8] Override Constructor
Hi there...

Okay just quick shoot...here...ok just curiousity here....from my digging and reading I know that we can't override constructor.....but might possiblity can be achieve...so I really need some shed on light from expertise people or some ideas how to achieve it...here's the my portions curiousity....


Code:

//let's say

class TestClass{
var __a:String;
var __b:Number

//==================constructor==============
function TestClass(a:String){
__a = a;
}

function TestClass(b:Number){
__b = b;
}
//==================constructor==============


}





//my curiosity is how to override constructor I mean give an options to me in order to to string params or numbers param2 either....

Code:
eg;

var test:TestClass = new TestClass("test");

var test:TestClass = new TestClass(2);

It is because my goal purposely wanna rectifying what of the datatype parameters being passing inside the class whether string or number..that's all is it possible....????
Any help are really appreciated

DispatchEvent In Constructor
ActionScript Code:
import mx.events.EventDispatcher;

class A extends EventDispatcher
{
   
    public function A()
    {
        trace("constructor called");
        dispatchEvent( {type:"onComplete", target:this} );
    }
   
    public function foo():Void
    {
        trace("foo called");
        dispatchEvent( {type:"onFoo", target:this} );
    }
   
}

ActionScript Code:
var a:A = new A();

a.addEventListener("onComplete", handler);
a.addEventListener("onFoo", handler2);

function handler(event:A):Void { trace("handler call back"); }
function handler2(event:A):Void { trace("handler2 call back"); }

a.foo();

Now i understand that the problem is dispatchEvent( {type:"onComplete", target:this} ); fires before the a.addEventListener("onComplete", handler); is ever added.

I'm sure there is a work around for having a dispatchEvent in the constructor, yes?

Date Constructor
heya,

i need flash to get Greenwich Mean Time (GMT) and display it in a dynamic text box. i also need the time to not be determined by the local machine, so that if your clock is off it doesn't affect the flash time.

i was wondering if anyone had any advise on how to accomplish this.

thanks

kris

Constructor Without Parentheses
I was trying to figure out the difference between the AsBroadcaster class and the EventDispatcher class, when I came across a construction that had me confused...

Is anyone aware of the purpose of calling a constructor without parentheses?

In the classfile for the EventDispatcher class, there is the following code:

PHP Code:



if (_fEventDispatcher == undefined)
        {
            _fEventDispatcher = new EventDispatcher;
        } 




Notice how the 'new' operator is called without trailing parentheses after the classname. I'm not familiar with this practice or the underlying implications.

Why and/or when would you want to do this? Does it have a different effect than calling the constructor with parentheses?

I do notice that there is no constructor function expilcitly defined for this class, so I'm assuming that Flash is implementing a generic no-arg constructor. However, without the parentheses, I fail to see how a 'new' call can instantiate an object. This seems more akin to attaching a function as an object method, but it doesn't seem that this is what's going on here.

Can anyone shed any light on the subject?

Constructor Parameters?
Is it possible to define constructor in a way that allows to pass undefined number of parameters?

Arguments Into A Constructor
Hi

I'm trying to get 2 arguments from a .fla to an external Class ...

my .fla says:

ActionScript Code:
var bigpic:BigPic = new BigPic(123,123);
    addChild(bigpic);

my Class says:


ActionScript Code:
package  {

    import flash.display.MovieClip;
    import flash.display.*;

    public class SS_Enlarge extends MovieClip {

        public var _xPos:Number;
        public var _yPos:Number;
               
        public function SS_Enlarge(xPos:Number=0, yPos:Number=0)
        {
            _xPos = xPos;
            _yPos = yPos;
            trace(xPos);
            trace(yPos);
            }
        }
}

the Class is linked to a clip in the library .

I keep getting error "1136: Incorrect number of arguments. Expected 0.

When i take the arguments away (123,123) it works ... but i need them in there .

What is this plonker doing wrong ?

Duplicate Constructor
Is it true that I cannot declare more than one constructor for a class?

Here's the situation. I'm using a class definition to declare a custom type like this:
Code:
package{
public class Class1
{
//... Variables

public function Class1():void
{
}
public function Class1(v:Class2):void
{
//Conversion from Class2 type
}
}
}
but the second constructor throws an error of a duplicate constructor.

If it's not allowed how can I do conversion from Class2 to Class1?

Constructor Best Practices
I was pounding out some classes today and got to thinking that there might be a better way to do what I'm doing. I find myself setting a lot of private variables in the class definition and then adding values to them and working with them in the subsequent constructor and class methods. I find myslef using the this keyword a lot and I don't know if maybe that is a no no or there is a more efficient way to do something. I'll provide you all some of my Franken code...


ActionScript Code:
package dt
{
    import flash.events.Event;
   
    import mx.containers.Panel;
    import mx.controls.Alert;
    import mx.core.UIComponent;
    import mx.events.MenuEvent;
   
    /**
     * ...
     * @author DefaultUser (Tools -> Custom Arguments...)
     */
    public class GUI extends UIComponent
    {
        private var mainPanel:Panel = new Panel;   
        private var layout:Page = new Page;
       
        public function GUI(w:Number,h:Number)
        {
            var mainPanel:Panel = this.mainPanel;
            var layout:Page = this.layout;
            var menu:dtMenu = new dtMenu();
            this.mainPanel.width = w;
            this.mainPanel.height = h;
            this.addChild(mainPanel);
            this.mainPanel.addChild(menu);
            this.mainPanel.addChild(layout)
            menu.addEventListener(MenuEvent.ITEM_CLICK,clickHandler);
        }
        private function clickHandler(e:MenuEvent):void
        {
            this.mainPanel.removeChild(this.layout);
            var call:String = e.item.data;
        }
        private function navigateMenu(e:Event):void
        {
            Alert.show(e.toString());
        }
    }
}

Date Constructor
Hi,
I saw different kind of scripts here about Date Constructor....
what is the easy script to put in my movie if i want
that a movie clip will play in a specific day ? and will continue .....to play

Ehud

Private Constructor
Hi,

I am just wondering why a constructor cannot be declared as private under AS 3.0?
It was possible under AS 2.0 and in many situation it may be logical to declare it as private, for example a class which instanciates its objects only through one of its public static classes.

Declaring a constructor as private just means that you don't want it to be instantiated by an external entity, doesn't it?

thanks

Override Constructor
Hi,

is it possible to override the Class constructor ?
thx.

RAF

Class And Constructor
Code:
class Iso {
private var xOrg:Number;
private var yOrg:Number;
//
function Iso(flashWidth:Number, flashHeight:Number, offsetY:Number) {
yOrg = flashHeight-offsetY;
xOrg = flashWidth/2;
}
//
private function yFla(xIso, yIso) {
return (yOrg-(yIso+xIso)/2);
}
private function xFla(xIso, yIso) {
return (xIso+xOrg)-yIso;
}
//
public function setPixelQuality() {
_quality = "LOW";
}
//
public function MoveIsoTo(x_iso, y_iso) {
_root.moveTo(xFla(x_iso, y_iso), yFla(x_iso, y_iso));
}
public function DrawLineTo(x_iso, y_iso) {
_root.lineTo(xFla(x_iso, y_iso), yFla(x_iso, y_iso));
}
}
i get an error:
**Error** C:Documents and SettingsBojan JazbinsekMy Documentsisoiso.as: Line 1: The class 'Iso' needs to be defined in a file whose relative path is 'Iso.as'.
class Iso {

tnx for help

AS2.0 Super Constructor
Hi. I am trying to build a class that inherits from the MovieClip class. Basically I am having issues in the constructor. Since MC's are unique in that they can only be created via createEmptyMovieClip or attachMovieClip, I am at a loss as to how you instantiate the inheriting class in the .fla? I figured if I just left the constructor out of the new class and do the following it would work but is doesn't:

ActionScript Code:
var hex:Hexagon = new Hexagon ();

How do I inherit from the MovieClip class and still instatiate the class using the above type actionScript?

BTW: I have seen alot of information about inheritance and AS1.0 (which I have little understanding of). I am trying to stick to OOP practices and AS2.0. I searched for things like super & constructor to no avail.

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