简体   繁体   English

无法将事件传递给addEventListener:closure问题

[英]Can't pass event to addEventListener: closure issue

This one's driving me crazy... I have a loop which adds an event listener to an SVG object. 这个让我疯狂......我有一个循环,它为SVG对象添加一个事件监听器。 The object is, for the sake of argument, a small circle, and I have to add mouseover and mouseout events for each of the 10 circles. 为了争论,对象是一个小圆圈,我必须为10个圆圈中的每一个添加mouseover和mouseout事件。

My first problem is the standard closure-scope thing - because all the listeners are added in the same loop, they all see the same invalid value of the loop variable. 我的第一个问题是标准的闭包范围 - 因为所有的监听器都添加在同一个循环中,它们都看到了循环变量的相同无效值。 I can fix this, I think, but the second problem is that I have to pass 'event' to the listeners, and I can't find any way to fix both these issues simultaneously. 我想,我可以解决这个问题,但第二个问题是我必须将“事件”传递给听众,而我找不到任何方法同时解决这两个问题。

I've tried various versions of this: 我试过各种版本:

for(month = 0; month < nMonths; month++) {
   ...
   shape.addEventListener(
     "mouseover", 
     (function(event, index) { popup_on(event, foo, index); })(event, month),
     false);
   group.appendChild(shape);
}

This particular version gives me 'event is not defined'. 这个特殊的版本给了'事件没有定义'。 popup_on is the real handler, and must get event and the current value of month . popup_on是真正的处理程序,必须获取event和当前month值。 Any idea how I should be doing this? 知道我应该怎么做吗? Thanks. 谢谢。

The event will be passed to your function automatically —just make it the first argument to the function you pass to addEventListener . 该事件将被传递给你的函数自动 -只是将其作为第一个参数传递给函数addEventListener Also, false is the default value for the capture parameter. 此外,false是捕获参数的默认值。

(function() {
    var i = month;
    shape.addEventListener("mouseover", function(e) { popup_on(e, foo, i); });
})();

Also, are you ok with foo being closed over in your event callback? 另外,你在事件回调中foo被关闭了吗? If not, you could do the same thing with it 如果没有,你可以用它做同样的事情

(function() {
    var i = month;
    var f = foo;
    shape.addEventListener("mouseover", function(e) { popup_on(e, f, i); });
})();

And if all these local variables are getting annoying, you can make them parameters to possibly make things a bit more tidy 如果所有这些局部变量都变得烦人,你可以使它们参数可能使事情变得更加整洁

(function(i, f) {
    shape.addEventListener("mouseover", function(e) { popup_on(e, f, i); });
})(month, foo);

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

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