If the environment supports the 3rd parameter in addEventLister
, that could is definitely better to use. However, if you need to work with legacy code (because you're working in an intranet, and/or you can't add a build step), you can have something like that:
var imgs = [img1, img2, img3, img4, img5];
for (var img, i = 0; img = imgs[i++];) {
img.onclick = function() { move.call(this); this.onclick = null; }
}
This will works mostly everywhere, even where addEventListener
is not supported at all.
But I wouldn't recommend this if you have the proper support of addEventListener
and at least ES6
; I just add this answer for the record. If you have at least addEventListener
(older IE doesn't, they've attachEvent
) you could at least have:
var imgs = [img1, img2, img3, img4, img5];
for (var img, i = 0; img = imgs[i++];) {
img.addEventListener("click", function listener() {
this.removeEventListener("click", listener, false);
move.call(this);
}, false); // in some browser the `useCapture` is still not optional
}
If forEach
is supported, the loop can be replaced with that.