简体   繁体   English

在javascript中更新事件函数中的全局变量

[英]Update global variable in event function in javascript

I think this question has been asked before but i was unable to find an answer, maybe I'm lacking the good words to describe my problem. 我认为这个问题之前已被问到,但我无法找到答案,也许我缺乏描述我问题的好词。

I have a loop in which, each iteration i create an object and I add an event listener which callback function uses the created object. 我有一个循环,其中,每次迭代我创建一个对象,我添加一个事件监听器,回调函数使用创建的对象。

for(var i in items)
{
    x = new SomeClass(i)

    someAPI.event.addListener(i, 'click', function(ev){
        x.someMethod()
    }); 
}

What happens, and I understand why, is the variable x within the event function definition is evaluated only when the event is triggered, and x is equals to the last value that has been affected to this name, which is the value given at the last iteration. 发生了什么,我明白为什么,事件函数定义中的变量x仅在事件被触发时被评估,并且x等于受此名称影响的最后一个值,这是最后给出的值迭代。

I would like to know how is it possible to get the wanted behavior, which is getting the current value of x in the loop, within the event function definition. 我想知道如何在事件函数定义中获得想要的行为,即在循环中获取x的当前值。 Thanks. 谢谢。

for(var i in items) {
    (function(j) {
        var x = new SomeClass(j);

        someAPI.event.addListener(j, 'click', function(ev){
            x.someMethod()
        });
    })(i);
}

The key is the var keyword, creating a new instance of the class on each iteration. 关键是var关键字,在每次迭代时创建类的新实例。
I added the IIFE to keep the value of i constant and to create a new scope on each iteration. 我添加了IIFE来保持i的值不变并在每次迭代时创建一个新的范围。

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

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