简体   繁体   English

在循环中分配的事件侦听器会触发所有事件

[英]Event listener assigned in a loop triggers all of them

Every object in the balls array is assigned an event listener that alerts the object's color, but when you click on just one, it activates all of them, alerting the color of every single object in it. balls数组中的每个对象都分配有一个事件侦听器,用于提醒对象的颜色,但是当您只单击一个时,它会激活所有对象,提醒其中每个对象的颜色。

Fiddle , snippet (listen):小提琴,片段(听):

function listen(obj, map, event, callback) {
  map.addEventListener(event, function (e) {
    if (hasPoint(obj.getBounds() || obj, event.clientX, event.clientY)) {
      callback.call(obj, e);
    }
  });
}

Loop (handler assignment);循环(处理程序分配);

for (var b = 0; b < balls.length; b++) {
  (function(b) {
      listen(balls[b], map, 'click', function(e) {
        alert(this.color); // where `this` === balls[b]
      });
  }(b));
}

(note: #listen is contained in an external file on GitHub - utils.js) (注意:#listen 包含在 GitHub 上的外部文件中 - utils.js)

How would I have each object only trigger its own event listener?我如何让每个对象只触发自己的事件侦听器?

The external util.js is key here, the listen function looks like外部util.js是这里的关键,listen 函数看起来像

function listen(obj, map, event, callback) {
  map.addEventListener(event, function (e) {
    if (hasPoint(obj.getBounds() || obj, event.clientX, event.clientY)) {
      callback.call(obj, e);
    }
  });
}

And you use it like你用它就像

listen(balls[b], map, 'click', function(e) {
    alert(this.color); // where `this` === balls[b]
});

Note that event in the listen() function is the string click , not the actual event, that would be e , so you want to use e to get the coordinates请注意, listen()函数中的event是字符串click ,而不是实际事件,即e ,因此您想使用e来获取坐标

function listen(obj, map, event, callback) {
  map.addEventListener(event, function (e) {
    if (hasPoint(obj.getBounds() || obj, e.clientX, e.clientY)) {
      callback.call(obj, e);
    }
  });
}

And that solves the issue这解决了这个问题

FIDDLE小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM