Object And Constructor Call
Hi:
I'm trying to learn AS and can't figure this point out. Say, if I want to create and initialize an Object variable of simple types I do this:
Code: var obj = {v1:0, v2:"Hello"}; But, what if I want to pass and initialize variables of my own class like this?
Code: var obj = {v1:Class1, v2:Class2}; //OK var obj = {v1:Class1(0, 1), v2:Class2("Hello")}; //Error: 1137
ActionScript.org Forums > ActionScript Forums Group > ActionScript 3.0
Posted on: 10-13-2008, 09:34 AM
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.
Class Constructor Won't Call Function
Hello,
I attached a pared down version of my .as file, which is imported into my flash (.fla) file. I can't seem to call the initCircularArray function from my class constructor. The trace function in the initCircularArray never gets called, and the onLoad(success) trace returns 'true'. Any idea what I might be doing wrong?
Thanks,
Dave
Attach Code
class CircularArray {
var circularArray:Array = new Array();
public function CircularArray(inXML:String) {
var newXML = new XML(); //the XML file
newXML.load(inXML);
newXML.ignoreWhite = true;
newXML.onLoad = function(success:Boolean) {
if(success) {
trace("XML loaded: " + success);
initCircularArray(newXML);
}
}
}
public function initCircularArray(newXML:XML) {
trace("
GOT HERE
");
}
}
Any Way To Call The Constructor From The Class One More Time?
In the AS3 help there is a remark, that a Class Constructor is just a method of the class, that is executed when an object of that class is created.
So, since the constructor is just a method of a class, how can i call it directly from the other class methods?
Object Constructor Help Needed
Hello
actionscript newbie here. My question is whether or not I can declare a constructor in a class that accepts parameters, thus allowing me to do things like
class MyClass {
...
function MyClass( thisvar:String, thatvar:String) {}
}
-------------------
var myInstance:Object = new MyClass( variable1, variable2);
is that possible? Please help! Thanks
Constructor On Library Object?
Hi,
I am currently migrating from AS 2.0 to 3.0.
In order to learn progressively and with simple examples, I created my objects in the library rather than doing separate *.as files.
I now would like to try the constructor definition feature.
I created a movieclip "MyClip" in the library, and activated linkage in first frame, as a clip extending flash.display.MovieClip.
But if I put this as code in the first frame of this movieClip:
Code:
function MyClip( xx:uint , yy:uint) {
trace ( xx );
trace ( yy );
}
I get the following error :
1021: Duplicate function definition.
Does that mean the constructor can only be used in *.as files, or am I missing something?
Any help would be greatly appreciated!
Object.constructor Property
<definition from ActionScript 2.0 Language Reference>
...constructor (Object.constructor property) ... Reference to the constructor function for a given object instance. The constructor property is automatically assigned to all objects when they are created using the constructor for the Object class ...
//--- --- - - -
i thought i understood this until i started doing some multiple level inheritance ..
imagine three classes:
-- class Object . . . (top level class)
-- class ParentClass . . . (implicitly inherits from Object)
-- class ChildClass extends ParentClass . . . (explicitly inherits from ParentClass)
and three objects:
-- var obj:Object . . . (an instance of Object)
-- var parentObj:ParentClass . . . (an instance of ParentClass)
-- var childObj:ChildClass . . . (an instance of ChildClass)
what we get:
obj.constructor == Object //-- as expected
parentObj.constructor == ParentClass //-- as expected
childObj.constructor == ParentClass //-- i would have thought it would be == ChildClass
//--- --- - - -
furthermore .. if i change my class definitions to be a bit less ambiguous:
class Object . . . (top level class)
class ParentClass extends Object . . . (explicitly inherits from Object)
class ChildClass extends ParentClass . . . (explicitly inherits from ParentClass)
what we get:
obj.constructor == Object
parentObj.constructor == Object
childObj.constructor == Object
//--- --- - - -
if this is the intended functionality of the constructor property i'm not sure i understand what its purpose is .. or am i completely misunderstanding something here .. if anyone has any answers i would be happy to hear them
also .. feel free to ask for clarification (if i was unclear) or more complete code samples.
Edited: 04/26/2008 at 02:16:39 PM by _peabulls_
Oo Constructor/init Object
I am experimenting with objects in order to pass parameters between methods.
If I have 2 objects the first is a paint brush and the instance is brush_mc,
everytime the brush is clicked it creates an instance of a paint blob on
screen, derived from paintBlob_mc.
My paint blob would have the following constructor code...
Code:
function PaintBlob (xPosition, yPosition) {
this.xPosition = xPosition;
this.yPosition = yPosition;
}
And my paint brush would have the following onPress code...
Code:
this.onPress = function () {
count = count + 1;
var paintBlob_mc" & count(_xmouse, _ymouse);
};
Am I thinking along the right lines? Does my code suck?
Sorry if Im boring everyone! I really wish our OO classes had used mx
instead of smalltalk and c++ I think I would have learned so much more.
Thank you for any input.
Possible? Access Object Constructor In Attached .swf?
Just want to know if this is possible. Seems to me it should be.
I'm working on movie.fla, in which I have a movie-clip symbol (mcBall) in my library (not on stage).
mcBall's symbol has a constructor built-in on frame 1.
function ball(color) {
this.color = color;
}
In my main movie (movie.fla), I do:
var newBallId = 'mcBall01';
attachMovie('mcBall', newBallId, 0);
I then want to create a ball object that coorelates to this movie clip, so I want to call the constructor that is embedded in the symbol (in frame 1)...
theBall = new _root[newBallId].ball('red');
if my constructor code lived in THIS timeline, the above line would look like
theBall = new ball('red');
Embedding the constructor in mcBall then calling it from movie.fla doesn't seem to be working... Anyone know if it's just not possible?
TIA
Register An Already Present Object To A Constructor
I am trying to create constructor object called "moveableObj".
I seem to have trouble figuring out how to use it or access it though.
Here is my code:
Code:
//create the constructor
moveableObj = function(ref){
//give it some property
this.test = "test";
}
//create a method()
moveableObj.prototype.moveBounce = function(args){
code here....
}
//attempt to register the class to an already present item on the stage with
//an instance name of mc_obj
Object.registerClass("_root.mc_obj", "moveableObj");
//attempt to access the method
mc_obj.moveBounce ();
//attempt to trace a property
trace(mc_obj.test);
There is obviously some problems in there.
1) If I have an already present MovieClip on the stage and want to assign it to the moveableObj constructor - how do I do that - I thought Object.registerClass but that seems to be if you have an item in the Library and are using Linkage - I am not.
2) Once I have the already present MC assigned to the moveableObj construstor - how can I call a method that will affect the assigned object?
e.g. mc_obj.moveBounce ();
Any help GREATLY appreciated - thanks!
How Can I Get A Method Onto The Math Object's Constructor Class?
From using an example in a book I have learnt how to add a method to the Math object. Now I know the Math object starts life as a ready formed Object when the Flash Player starts, but how can I place my intended method so that it is available to ALL Math objects not just the one I’m working with at that time?
Normally to achieve the above I would place the method on the “prototype” object of the constructor, but with Math I only have the object name not the class to put the method upon & the Math object is already defined before I get a chance to code anything.
Calling Constructor In Condition: A Function Call On A Non-function Was Attempted.
Hi guys,
Please help me somebody with this cos I have really no idea. I have made a simply condition calling a constructor of a class. Today I had to add an "else if", what caused the compilator to show me "A function call on a non-function was attempted."...
ActionScript Code:
function loadIt() { if (var1 == "1") { var a:SomeClass = new SomeClass(true); } else if(var2 == "1"){ var a:SomeClass = new SomeClass(false); //<- if this is not here, everything works fine } else { var b:SomeOtherClass = new SomeOtherClass(); b.init(); }}
Any ideas? Thanks for any help!
Poco
Video Object - Call To Load And Listener Object Not Working
i've got a video object within a movieclip who's full path i put in a var called 'video'. here's my code, it appears that the video object is not loading my stream and/or i'm not getting the listener object to work properly... everything does trace out good as far as vars, rtmp address, etc... grrr!!!
Code:
//function to load the stream in the vid object
_global.loadVid=function(vidFile){
trace("this is path to vidObj: "+video);
trace("loadVid function var passed: "+vidFile);
var listenerObject:Object = new Object();
listenerObject.ready=function(eventObject:Object):Void{
//video loaded, do this
video.removeEventListener("ready", listenerObject);
_root.container.vidPanel.gotoAndPlay("tovideo");
trace("video is loaded, proceeding to video play state");
};
video.addEventListener("ready", listenerObject);
var nV:String=rtmpURL+vidFile;
video.load(nV, true);
trace("video: "+rtmpURL+vidFile+" should be loading");
}
So An Object Can't Call Another Object's Methods?
Say I have a conveyor belt object and a trailer truck object.
The conveyor belt adds boxes to itself.
The user clicks on a box and then clicks on 1 of three trailer trucks to put it in.
When box is placed in 1 of the 3 trucks, I'd like the trailer truck to call the conveyor belt's method to cause the conveyor belt to 'add a box' to itself.
If a box is not placed after 4 seconds, the conveyor belt is to call it's 'add a box' method to add another box to itself.
Since the trailer truck mc is also defined as a button, I check to see if it's been clicked on as a way of knowing if a box has been placed inside it and therefore another box should be added to the conveyor belt.
Is it possible to do it this way with oop? I can't seem to do it, but maybe I've got the syntax wrong. If not, how might it be set up with proper oop?
Call On A Object
I have a movie that has three layers. one layer has a piece of text. the next layer contains a box and then the last layer is the back ground. I want the piece of text to slide in first then at a certain time during the movie, i want the box to slide in. how do i make objects wait until they are called on
Flash / URL Call / XML Object
HI,
I need to make a URL call from flash to a server and receive a xml object as an answer.
Is posible to do that with action script 2?
Any ideas will be very appreciated.
Tks.
Dynamically Call A Certain Method Of A Certain Object.
Hi I have a method "callerMethod()" that accepts 2 arguments:
1.myObject: a reference to an object in my flash movie (object)
2.myMethod: a name of a method in myObject (string)
now, I'd like callerMethod() to invoke myObject.myMethod()
Tried different combinations of eval() and this[] but no luck.
How can I make this work?
Thanks
LeoBeer
LoadMovie() Object Call Problems
Hello all,
I just implemented a loadMovie function in for my preloader on the site I'm currently working on for work. It works great locally (I was having troubles w my previous one bc it had too much file data to load on frame 0 so the preloader wouldnt start until it was about 80% complete, this works much better... theoretically)
However, when using the preloader .swf in the flash file it does not work at all, it merely loops through the preloading animation without ever calling in the larger file it was supposed to.
mcLoader.addListener(listener);
mcLoader.loadClip("ban_spaTime.swf", container);
That is the swf it should be calling. I have the preloader and the swf in the same folder online - I have tried putting in the entire http link but that doesnt work either. Anyone have any suggestions or is this a limitation of that call?
thanks for any help
-c
How To Call A Referenced Object.method
hello;
I am trying to call a class.method using a reference to the class:
my_class = function()
{ this.listener_method = function( args )
{ trace( args ) ;
}
my_object.register_something ( this , "listener_method" ) ;
}
my_object = new Object();
my_object.register_something = function( arg_reference_to_class_or_object , arg_method )
{ // ?????????????????
arg_reference_to_class_or_object.arg_method( "howdy" ) ;
// so here I want to use the received arguments to call back;
// in Lingo I just use 'call' but Flash's 'call' does something different;
};
any thoughts?
thanks
dsdsdsdsd
Easy Help Please - Using A String To Call An Object
Hi there,
Please help me understand why this does not work;
PHP Code:
this.floorplan.butt01.onPress = function(){ floorplan.alphaTo(0, fadeOutTS, fadeOutTT, 0, 'revealNext(1)');}function revealNext(num){ revealMC = ["page_"+num] trace(revealMC);}
This returns a string value, page_1 (instead of the usual Object path), but alas, if i change this one line to;
PHP Code:
revealMC = _root["page_"+num]
it will return the Object path (using 'this' doesnt, as i presume its reffering to the function). i can also put it in an MC on the stage, called "pages" and do;
PHP Code:
revealMC = pages["page_"+num]
please, please save me from this!
Many thanks,
Loque
Best Way To Call Events In Sound Object
I am playing a series of sound files via actionscript 3.0, and I would like to have a fade out effect for each sound and then have the next sound fade in.
I was just curious if anyone could think of a better method then to have an enterframe listener check every frame the position of the song? Or would a timer be better suitable?
Or maybe something else all together? I'm just afraid that the listeners will mess up if a user's machine locks up...
Thanks,
-Danny
SWF Object / External Interface Call
Hey Guys,
I am currently just finishing a project and I am having a big time problem with an ExternalInterface call.
My application runs fine but when the javascript call is being made from flash using external interface, IE is going from the "Done" message, to showing the "!" icon, with "error on page" as the message.
There is no error that is showing up in Firefox.
The current error I am seeing is an 'Unterminated String Constant', which wouldn't be a problem except for that it appears on line 1... which is
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
So anyways, if anyone could give me a hand it would be a great help.
Thanks,
--d
How Do You Define An Object In Call Function Using A Varible ?
Please please please somebody answer , i've had this problem before when scripting and never managed to get round it .
I've tried using eval and all sorts of other stuff but never managed to get it to work.
for (i=0; i<split1.length; i++) {
temp = split1[i].split(":");
eval("_parent."+ split[1]).loaded();
}
Is the script , i just want to call a function in a few objects which are loaded from an array.
AS: Object-Oriented Call Of Event-hander?
Hello!
Imagine the following class, which loads another movie-clip and assigns an onPress function, which should call the class itself:
PHP Code:
class MyClass extends MovieClip
{ public var m_sTeststring = "Parent-Class";
public function MyClass()
{ var pPic:MovieClip;
pPic = createEmptyMovieClip("pic"+nCount, nCount);
pPic.loadMovie(sUrl); // sUrl: URL of a picture to be loaded
pPic.m_sTeststring = "Picture";
pPic.onPress = this.onClickPic;
trace(m_sTeststring); // Outputs "Parent-Class";
}
public function onClickPic()
{ trace(m_sTeststring); // Outputs "Picture"
}
}
The result is, that onClickPic is called in the context of pPic and outputs "Picture" instead of "Parent-Class".
Why is this and how can I make the onPress-Event refer to the instance of my class WITHOUT using absolute pathes like _root.myclass1.m_sTeststring?
AttachMovie, Function Call, Undefined Object
I have created a function on my timeline:
function changeInstText(thisMovie, thisReplacement, thisName)
{
trace("Button called changeInstText()");
var whatMovie:MovieClip = thisMovie;
var whatReplacement:String = thisReplacement;
var whatName:String = thisName;
trace(emptyText_mc);
trace(whatReplacement);
trace(whatName);
whatMovie.attachMovie(whatText, whatName, 0);
}
which gets called from a movieClip button that is within a movie on my stage.
on(release)
{
this._parent._parent.changeInstText("_root.callOut MenuAnim_mc.callOut_mc.emptyText_mc", "txtChng1", "txtName1");
}
*I also tried this._parent._parent.changeInstText("emptyText_mc" , "txtChng1", "txtName1");
that is trying to change a movie within another movie, two layers deep, that is on my stage called emptyText_mc.
When I trace whatMovie from the function it says it is undefined.
What am I doing wrong? I have attached the file so you can see what I mean
How Do You Call An Object That Only Appears In Specific Frames?
I am practicing with my actionscript and encountered a problem.. Previously, my main movieclip has only 1 frame. I have a dynamic textfield (myText_txt) already in the stage in frame 1.
in my actions page, i have myText_txt.text = "hello".
so when i play my movie, hello appears in my textfield.
Then, i decided to move the textfield from frame 1 into frame 2. Suddenly, flash cant detect myText_txt anymore... Cannot access a property or method of a null object reference.
my actions page looks something like this now:
function initialize():void
{
this.stop();
this.gotoAndStop(2);
myFunction();
}
function myFunction():void
{
myText_txt.text = "hello"
}
initialize();
Why is this? i extended my very first layer which is my action layer all the way to layer 10... dunno if this is required though. But still doesnt work. Why can't flash detect my myText_txt? Oh, in the new frame 1, myText_txt is not yet in the stage.
Listener VS Simple Object.function Call
I know that listeners allow multiple Class to listen to one object. In the other way if there is only one object that must listen or react when an event is triggered, we can simply use the object reference and by that reference calling the function. For example if we have 2 Classes A & B.
First Option : Class A is the object that dispatch an event when a transition is completed. CLass B can listen all events from Class A and the execute a function when the Class A transition is done.
Second Option : Class A has a reference of Class B. When Class A transition is completed, Class A use the Class B reference to execute a function in the Class B.
The 2 options does the same thing. The only diffrence is that in the first option, many objects can react to the end of the Class A transition.
What I'd like to know, is what is the best way. I mean, If I only have one Object that listen to the Class A Events. Is that a better way to use object reference? Does the Listener are slower to execute instead of a function call from a reference? Does...
Listeners take more code to execute, must be removed when the Class is removed. May be I there is more to know then that.
Any opinion or suggestion?
Dynamically Call A Variable In A Local Shared Object
Hi,
My application will plant a local shared object on the user's machine, the SO will hold 20 strings (myString0,myString1.....)
the users will browse through the application and will have to call a different string each time.
unfortunately the script below wont work:
Code:
mySO = sharedobject.getLocal("test");
mySO.data.myString1 = "hello world";
i = 1;
stringThis= new String;
stringThis = this["mySO.data.myString"+i];
trace("stringThis:"+stringThis);
this simple code will not result in the output: "stringThis:hello world".
the simple syntax we use to dynamically call variables or objects will not work here.
any ideas?
Thanks.
Pass Class Object To FMS Using NetConnection.call Method
Hello All,
I have a custom class that defines several methods on itself to retrieve its data. This class object is then sent to FMS via the NetConnection.call method. Once received by FMS, FMS calls the remote method to dispaly the class object on connected clients (minus the originator).
Now, standard properties are displayed correctly, but when I call the class method to retrieve the class data, no data is retrieved.
My question is, can FMS handle class objects as parameters in a NetConnection call. If not, is there a better practice of applying methods to retrieve the class data? Example below...
class com.QuizItem
{
var numOfAnswers;
var getAnswer;
function QuizItem(question)
{
this.numOfAnswers = 0;//<-- Returns correct number of answers
this.getAnswer = function(answerNumberToGet)//<-- Does not return any data when called by client side script
{
return this.answers[answerNumberToGet];//Already populated array
}
}
}
Regards,
Shack
Can't Call Function Created Via Eval Using ExternalInterface.call
I have created a flash movie that acts as an MP3 player. Using ExternalInterface, I pass an array containing cue points in the song to the flash move so that it makes a callback to javascript when it hits certain points in the song. Since I want to deal with these callbacks differently for each song, I have made it so that I can dyanmically change the function that is called from Flash (to Javascript). Here is the code for that piece:
ExternalInterface.addCallback("setCuePointFunction ToCall", this, setCuePointFunctionToCall);
var cuePointFunctionToCall:String='';
var intCurrentCuePoint:Number=0;
function setCuePointFunctionToCall(strFunctionName){
_root.cuePointFunctionToCall=strFunctionName;
}
function reportToJavascript_CuePoint(intCuePointID:Number){
ExternalInterface.call(_root.cuePointFunctionToCal l, intCuePointID);
_root.intCurrentCuePoint++;
}
This works perfectly as long as the function that cuePointFunctionToCall refers to is defined in a script block on the HTML page. However, this project is an AJAX-style thing, and I need to be able to define the function that is triggered on a cue point in code that is dynamically executed at run-time via an "eval' call.
Here's the code that talks to actionscript. This appears in a script block on the main page (not via eval).
function setCuePointFunctionToCall(strFunctionName) {
thisMovie("PushPuppets_Media_Center").setCuePointF unctionToCall(strFunctionName);
//alert(strURL);
}
function thisMovie(movieName) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName];
}
Here's the code that is dyamically being executed via an eval statement in javascript:
setCuePointFunctionToCall("cuePointNew");
function cuePointNew(lngCuePointID) {
alert('New function, cue point: ' + lngCuePointID);
}
This does not work. But if I copy the above function block to the main page (not in the code that is executed via an eval) it does work. I am certain that setCuePointFunctionToCall is being executed properly via the eval - it is definitely changing the function that actionscript will call. This is apparent since it is calling the right function when the function is declared on the HTML page (not in the AJAX-style eval call). So I'm guessing that this has something to do with the scope in which eval operates.
I encountered a very similar problem when I tried redefining a function in the eval call that was already defined on the main page. It just didn't take.
Please let me know if you have any suggestions.
Thanks,
Erich
[]'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?
|