简体   繁体   English

在element.bind中实现闭包-角度

[英]Implementing closure in element.bind - angular

I'm binding an event to an element in directive and want to pass the loop variable. 我将事件绑定到指令中的元素,并希望传递循环变量。 How can I do this using closures ? 如何使用闭包呢?

for(var i=0; i<events.length; i++) {
     switch(events[i]) {
               case 'focus' :
                 var m = i;
                 element.bind('focus', function(event) {
                    console.log(m);
                 });
               break;

               case 'blur' :
                 var n = i;
                 element.bind('blur', function(event) {
                    console.log(n);
                 });
               break;        
     }
 }

In the above code I'm using variables m and n but how can I do it without them ? 在上面的代码中,我使用变量m和n,但是如果没有变量我该怎么办呢?

I also tried 我也试过

 element.bind('focus', function(num, event) {
    console.log(num);
  }(i));

But it didn't work 但这没用

Demo : http://plnkr.co/edit/gwthMUkXXCQfZYr4bHLg?p=preview 演示: http : //plnkr.co/edit/gwthMUkXXCQfZYr4bHLg?p=preview

Create a separate function which you can call by passing i and which returns a function, thus creating a closure, which has the number which you're passing, in context. 创建一个单独的函数,您可以通过传递i来调用它并返回一个函数,从而创建一个闭包,该闭包在上下文中具有要传递的数字。

function callback(num) {
   return function(event) {
     console.log(num);
   }
}

Now you can just bind it like this 现在您可以像这样绑定它

element.bind('focus', callback(i));

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

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