将局部变量传递给回调函数 [英] Pass in local variable to callback function

查看:216
本文介绍了将局部变量传递给回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

回调函数如何保留创建它的局部变量?

How can a callback function retain a local variable from whence it was created?

简单示例

我正在制作视频播放器。它将有滑块来控制饱和度,对比度和色调。当用户使用滑块时,它需要确认哪个滑块已更改以及更改了哪个值。问题是滑块的名称是来自此onChange回调的创建者范围的局部变量。该回调如何保留滑块的名称?

I'm creating a video player. It will have sliders to control the saturation, contrast, and hue. When the user plays with the sliders, it needs to acknowledge which slider got changed and what value it got changed to. The problem is that the name of the slider is a local variable from the scope of the creator of this onChange callback. How can this callback retain the name of the slider?

HTML

<div id="saturation">
 <div class="track"></div>
  <div class="knob"></div>
 </div>
</div>

<div id="contrast">
 <div class="track"></div>
  <div class="knob"></div>
 </div>
</div>

<div id="hue">
 <div class="track"></div>
  <div class="knob"></div>
 </div>
</div>

JS

var elements = [
 'saturation',
 'contrast',
 'gamma'
];

for(var i = 0; i < sliders.size(); i++) {
 new Control.Slider(
  $(elements[i]).down('.knob'),
  $(elements[i]).down('.track'), {
   onChange: function(value) {
    // ERROR: elements[i] is undefined
    alert(elements[i] + ' has been changed to ' + value);
   }
 }
}


推荐答案

同一个变量 i - 谁的价值最终结束是4 - 绑定到你在循环中创建的每个函数。你可以将函数包装在你当场调用的另一个函数中,并将 i 作为参数传递给该函数:

The same variable, i — who's value ends up being 4 — is bound to every function you create inside the loop. You could wrap the function in another function that you call on the spot and pass i as a parameter to that function:

for(var i = 0; i < sliders.size(); i++) {
 new Control.Slider(
  $(elements[i]).down('.knob'),
  $(elements[i]).down('.track'), {
   onChange: (function(inner_i) { function(value) {
    alert(elements[inner_i] + ' has been changed to ' + value);
   } })(i)
 }
}

这篇关于将局部变量传递给回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆