Javascript Looping Object Instance’s Method Problem
Posted by Kyle Weems on June 03, 2009Time 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?
Tags: confused, javascript, kung fu
This scope of the callback function changes, so when you say “this.greet” inside the callback function, it thinks “this” is the callback function, not the original object.
One really easy way to get around that:
var myObj = this;
if(this.count < 2) {
$('body').animate({"opacity":1}, 1000, function(){myObj.greet();});
}
That should take care of it.
@Dan – I thought it was a scope issue, but I just couldn’t figure out how to sidestep that.
Thanks! That seems to have nailed the issue I was having.
You, sir, are awesome and deserve a piece of cake.
I, sadly, don’t have any cake to give you.
@Kyle No cake? What a ripoff(:
Glad to help.
You could always follow http://twitter.com/ioubeer (http://foamee.com/)and @danieltott.
Rather freakily somebody has @ioubeer’d dan lately!