Using CreateJS, I have output a canvas with instances of various objects, animating in various ways. Almost all is working ok, except for one issue, which I think is a scope issue, but I'm not sure how to fix. I have an instance referenced by '_pulsars', containing 11 instances of an object 'pulsar', and code runs like this:
function attachPulseFuncs() {
var defaultFreq = 0.05; // controls the likelihood of a 'pulse' happening
for (var i = 0; i < _pulsars.children.length; i++) {
var myParent = _pulsars.children[i];
myParent.isPulsing = false;
_myParent.pulse = function() {
if (myParent.isPulsing == false) {
myParent.isPulsing = true;
myParent.__frame = 1
var tween = createjs.Tween.get(myParent).to({__frame:65}, 1500).call(myParent.resetPulse);
tween.addEventListener("change", function() {
myParent.gotoAndStop(myParent.__frame);
});
}
}
myParent.resetPulse = function() {
myParent.gotoAndStop(1);
myParent.isPulsing = false;
}
myParent.callRandomPulse = function() {
var ran = Math.random();
if (ran < freqNumber) {
myParent.pulse();
}
}
createjs.Ticker.addEventListener("tick", myParent.callRandomPulse);
}
}
What happens is that only the last pulsar animates (no matter how many are in the group). I'm wondering if it's because only one event listener is being attached? Or somehow all the listeners are being added to one 'pulsar'? Please help!
EDIT: Success! Thanks to Robert (and also Bergi's link to the similar issue), I was helped to understand a little more about closure and unbinding the variable being passed into the function - as the link on the other thread says:
"if we pass a parameter [the] function makes its own local copy of the variable (if it is not object type which pass by reference)"
This allows each pulsar to have a discrete reference to its parent as defined by each iteration of myParent, rather than the single outer-scope reference that was being held by the final value of myParent. (@Robert Koritnik please let me know if I have misunderstood or this is incorrect! Thanks for your help, I would +1 if I wasn't so new to the site. Soon, hopefully)