PDA

View Full Version : can't call custom class method in loop?


chackel
10-03-2003, 03:41 PM
This is a bizzare problem.
Hopefully one of you gurus will be able to figure it out.

I have a class "TestSymbol" (extends MovieClip) with two methods and a "getId" method:
1) sayHi() : prints this.getId() + "hi"
2) sayMessage(msg): prints this.getId() + msg 10 times.

I attach 3 instances of TestSymbol:
this.attachMovie("TestSymbol","t1",1)
" "t2",2)
" "t3",3)

then I put the instances in an array:
moviearr=[this.t1,this.t2,this.t3];

Now, if I loop through the array calling "sayHi" I get:
1 hi
2 hi
3 hi

But, if I loop through calling sayMessage, I only get t1 printing the msg 10 times.

Any ideas?? I've attached the code.

Thanks!
Chris

webguy
10-03-2003, 03:45 PM
can you show your loop?

Exchange sayHi trace("hi") with sayHi trace(this) and see if it is indeed incrimenting through the loop.

webG

chackel
10-03-2003, 03:53 PM
I tried that..
1: hi _level0.test1
2: hi _level0.test2
3: hi _level0.test3

Here is the code:
Movie Script:
-------------
var initObj=new Object;
initObj.cp_id=1;
this.attachMovie("TestSymbol","test1",1,initObj);
initObj.cp_id=2;
this.attachMovie("TestSymbol","test2",2,initObj);
initObj.cp_id=3;
this.attachMovie("TestSymbol","test3",3,initObj);

moviearr=[this.test1,this.test2,this.test3];

message="Hi there!";

trace("first, loop through all instances calling a 1 line function");

for(i=0; i<moviearr.length; i++)
{ moviearr[i].sayHi();}

trace("next, call handleMessage (function w/ a loop) for each instance one-by-one");
this.test1.handleMessage(message);
this.test2.handleMessage(message);
this.test3.handleMessage(message);

trace("finally, call handleMessage for all instances in a loop");
trace("this only calls the function for the first instance");
for(i=0;i<moviearr.length;i++)
{
moviearr[i].handleMessage(message);
}






TestSymbol script:
----------------
#initclip

//Constructor
_global.TestSymbol=function()
{
trace("constructor called: "+this.cp_id);
this.id=this.cp_id;
delete this.cp_id;
}

// Set MovieClip as TestSymbol's superclass
_global.TestSymbol.prototype=new MovieClip();

//Put in lib
Object.registerClass("TestSymbol", _global.TestSymbol);

//METHODS

_global.TestSymbol.prototype.handleMessage=functio n(mes)
{
trace("handle message called: "+this.getid());
for(i=0; i< 10; i++)
{trace(this.getId()+": "+mes);}

}

_global.TestSymbol.prototype.sayHi=function()
{trace(this.getId()+": hi");}

_global.TestSymbol.prototype.getId=function()
{
return this.id;
}

#endinitclip

chackel
10-03-2003, 04:42 PM
*var* i in "handleMessage"
fixes the problem.


for(i=0; i< 10; i++)
{trace(this.getId()+": "+mes);}