function initCircles() {
circles = [];
for (var i = 0; i < 100; i++) {
var circle = new createjs.Shape();
var r = 7;
var x = window.innerWidth * Math.random();
var y = window.innerHeight * Math.random();
var color = colors[Math.floor(i % colors.length)];
var alpha = 0.2 + Math.random() * 0.5;
circle.alpha = alpha;
circle.radius = r;
circle.graphics.beginFill(color).drawCircle(0, 0, r);
circle.x = x;
circle.y = y;
circles.push(circle);
circle.movement = 'float';
circle.addEventListener("mouseover", function(event) {
circle.graphics.clear().beginFill("red").drawRect(0, 0, 50, 60).endFill();
stage.update(event);
});
stage.addChild(circle);
}
}
I'm trying to add a mouseover listener on the little circles I create on the page, I hope that once I place the cursor on the circle, it becomes a rectangle. However, the rectangle always appear where some other circle exists rather than the circle I point to.
The problem is that you are referencing a mutable variable inside of the closure. There are a couple of ways to solve that.
1) Either somehow reference the circle from the event variable inside of the nested function (if the event has support for that), or
2) Bind the value of the variable inside another function, e.g:
function initCircles() {
circles = [];
for (var i = 0; i < 100; i++) {
var circle = new createjs.Shape();
var r = 7;
var x = window.innerWidth * Math.random();
var y = window.innerHeight * Math.random();
var color = colors[Math.floor(i % colors.length)];
var alpha = 0.2 + Math.random() * 0.5;
circle.alpha = alpha;
circle.radius = r;
circle.graphics.beginFill(color).drawCircle(0, 0, r);
circle.x = x;
circle.y = y;
circles.push(circle);
circle.movement = 'float';
addEventListener(circle);
stage.addChild(circle);
}
function addEventListener(circle) {
circle.addEventListener("mouseover", function(event) {
circle.graphics.clear().beginFill("red").drawRect(0, 0, 50, 60).endFill();
stage.update(event);
});
}
}