简体   繁体   English

Raphael.js - 向元素注册多个事件

[英]Raphael.js - registering multiple events to element

my problem is that I need handle multiple events for rectangle. 我的问题是我需要处理矩形的多个事件。 That sound simple, for example this works 这听起来很简单,例如这有效

  node.click(function(e){
     click(); // this is function defined in same scope, it works ok
  });

  node.mouseout(function(e){
     mouseout();  
  });

But, I want to automatize this, so it should looks like this: 但是,我想自动化这个,所以它应该是这样的:

var events = new Array("click", "mouseout");
for(var i in events){
     node[events[i]](function(e){
         events[i](); /*THIS is problem, no matter if it is click or mouseout
                        this always fires function with same name as last item
                        in events array (in this case mouseout) 
                      */
     }
}

Do you have any idea why a how I should solve it? 你知道我为什么要解决这个问题吗?

Your handlers created in a loop are sharing a variable. 在循环中创建的处理程序正在共享变量。 By the time they are called, the variable is the last value in the loop. 调用它们时,变量是循环中的最后一个值。

You have to use a technique I call "freezing your closures" so that each handler gets a separate copy of the shared variable. 你必须使用我称之为“冻结闭包”的技术,以便每个处理程序获得共享变量的单独副本。 In your case, the shared variable that changes is i 在您的情况下,更改的共享变量是i

Your other problem is that you want to call your functions "click/mouseout" from a string, so you have to get a handle to the function, right now your code is attempting to call "hello"() which does not work 你的另一个问题是你想从一个字符串中调用你的函数“click / mouseout”,所以你必须得到一个函数的句柄,现在你的代码试图调用"hello"()这不起作用

Your last problems (but not a bug yet) are that you shouldn't use the Array constructor and you shouldn't use a for in loop to iterate over arrays. 您的最后一个问题(但尚未出现错误)是您不应使用Array构造函数,并且不应使用for in循环来迭代数组。

function createHandler(eventName) {
    return function(e) {
        window[eventName]();
    }
}

var events = ["click", "mouseout"];
for(var i=0; i < events.length; i++){
     node[events[i]](createHandler(events[i]));
}

The above example is easier to comprehend but you could use self invoking anonymous functions to do the same thing 上面的例子更容易理解,但你可以使用自调用匿名函数来做同样的事情

var events = ["click", "mouseout"];
for(var i=0; i < events.length; i++){
     node[events[i]]((function(eventName){
         return function(e) {
             window[eventName]();
         };
     })(events[i]));
}

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

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