2

I am looking for best way how to bind one method for multiple objects in JavaScript.

What I need to do is to create multiple objects in runtime and then bind them the same functionality let say "change color on mouse over".

I have method:

function changeElement(element) {
  element.fill({
    r: ~~(Math.random() * 255),
    g: ~~(Math.random() * 255),
    b: ~~(Math.random() * 255)
  });
}

and I have code:

for (i = 0; i < 5; i++) {
  var r = draw.rect(50, 50);
  r.move(i * 80, 100);
  r.mouseover(function() {
    changeElement(r);               // <-- this is not working
  });
};

but is not working for all objects in loop just for last one.

I am doing something wrong but I don't know what.

Full example here https://jsfiddle.net/mojno7/2ysowx5u/.

mojmir.novak
  • 2,920
  • 3
  • 24
  • 32

0 Answers0