Using jQuery to animate HTML objects is fun. These animations are easy to create and there are many good documents with explanations and examples.
Unfortunately I haven't noticed the information in the jQuery API about "this" in its callback function. The animate-Method replaces "this" with the used DOM-element. If you are trying to program object-oriented with JavaScript, you can easily run into problems.
Here is a little snippet from our game "Doggie Dodge" (working title) to illustrate the problem. The wrong code:
Board.prototype.moveCat = function() {
// ...
// As soon as the cat moved, all dogs should start moving
$('#cat').animate({
'left' : '+= 20px',
'top' : '+= 20px'
}, {
'duration' : 'fast',
'complete' : function() {
this.moveDogs();
}
});
// ...
}
To get this code right, you have to replace "this" through a variable:
Board.prototype.moveCat = function() {
// ...
// As soon as the cat moved, all dogs should start moving
var myBoard = this;
$('#cat').animate({
'left' : '+= 20px',
'top' : '+= 20px'
}, {
'duration' : 'fast',
'complete' : function() {
myBoard.moveDogs();
}
});
// ...
}
Add new comment