Reputation: 33
I have instances of jPlayer (jquery audio player): jPlayer1, jPlayer2, jPlayer3, jPlayer4, each initialized and preloaded with audio files.
Calling function below will traverse an existing array and adding the methods that plays the preloaded audio.
function addPlayAudioMethodToExerciseArray(){
for (i in qaArray){
qaArray[i].playAnswer = function(){ $('#jPlayer'+i).jPlayer('play',0);}
}
}
It creates the method alright except for the part ('#jPlayer'+i) is not evaluated to become ('#jPlayer1'), ('#jPlayer2'), etc.
Many thanks in advance. Note: I'm a noob.
Upvotes: 0
Views: 739
Reputation: 414086
The problem is that all those "playAnswer" functions are wrapped around the very same "i" variable. That is, there's only one "i" (and in this case, since you didn't declare it with var
, it's global!).
What you need to do is use another function to provide a separate "i" for each one of the callbacks.
function addPlayAudioMethodToExerciseArray(){
function makePlayerCallback(i) {
return function() {
$('#jPlayer' + i).jPlayer('play', 0);
};
}
for (var i = 0; i < qaArray.length; ++i){
qaArray[i].playAnswer = makePlayerCallback(i);
}
}
The "makePlayerCallback" function has its own parameter "i", which, being effectively local to that function, will result in callback functions that have their own "i" individually. Each call to that function creates what's called a "closure" around the returned callback function. (Note that my loop starts at zero; if your identifiers in the HTML start at 1, you'll need to account for that by adding 1 somewhere. Thanks to @DieVarDump for that note.)
Note that I declared the "i" used in the loop with var
to make it local to "addPlayAudioMethodToExerciseArray" (boy that's a long function name; I hope you won't have to type it too often :-). Also, I used it as a numeric index, under the assumption that"qaArray" is really an honest-to-gosh array, and not just n object. It's good practice to use numeric indexing for arrays.
Upvotes: 2
Reputation: 148744
use colsures
try this :
for(i in qaArray)
{
qaArray[i].playAnswer = function (num)
{
return function ()
{
$('#jPlayer' + num).jPlayer('play', 0);
} ;
}(i)
};
Upvotes: 0