Posts Tagged ‘confused’

Javascript Looping Object Instance’s Method Problem

Wednesday, June 3rd, 2009

Time to expose some of my JavaScript weaknesses.

I’m working on a side-project that has multiple instances of the same object (or the equivalent in JS) that makes use of jQuery’s .animate function. At the end of the animate function I want to use .animate‘s callback function option to loop the function in each object (allowing each to loop through a frame-by-frame animation of its own, for example).

The problem is I’m running into an obstacle, which can be illustrated by this simplified looping example. In this particular case, when you click on the button, it creates an instance of the object, sets a value inside it, then calls an internal function which displays an alert box, then calls a (in this case pointless) jQuery .animate function which contains a callback function to loop the instance’s function. The idea would be that I can call multiple instances of the object, and have each assigned their own values and then they’ll loop happily on their own.

That’s not happening, of course.

If you examine the JS source code (linked here) you’ll see that I use function(){this:greet();} as my callback parameter. My understanding was that this would correctly relaunch the function of the instance. It does not, however, work as I desire (aka, at all).

I know that this is an odd thing, so I’m sure I’m hamfistedly trying to pound a square peg in a round hole. The trouble is that I have absolutely no clue what the round peg is.

What I really need is a Master Po to tell me where I’m going horribly wrong here. Can anyone be my blind kung fu mentor?