迭代期间的回调范围
我知道有很多关于回调、范围和闭包的问题。如果这是重复的,我提前道歉。
我有一个each 循环,它调用一个执行多个异步操作的函数,然后发出回调。当回调触发时,我(显然)失去了范围。我所做的是将循环中的项目传递给函数,然后在回调中返回它,这样我就有了我需要的范围。这是最好的方法吗?我并不是在寻找过于复杂的东西。我只是想确保我不会遇到任何“陷阱”。
function doSomething(varA, varB, self, callback) {
// do a lot of ajax stuff
callback(varA + varB, self);
}
$.each( $('.selected'), function(i, item) {
doSomething('a', 'b', item, function(retVal, self) {
// process retVal and self
}
}
I know there are a ton of questions regarding callbacks, scope, and closures. I apologize in advance if this is a duplicate.
I have an each loop that calls a function that performs several async actions and then issues a callback. I'm losing scope (obviously) when the callback fires. What I've done is pass the item in the loop to the function and then I return it in the callback so I have the scope I need. Is that the best way to do this? I'm not looking for something overly complicated. I just want to make sure I'm not going to run into any "gotchas".
function doSomething(varA, varB, self, callback) {
// do a lot of ajax stuff
callback(varA + varB, self);
}
$.each( $('.selected'), function(i, item) {
doSomething('a', 'b', item, function(retVal, self) {
// process retVal and self
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你所得到的看起来不错,但有一件事:使用
$.each()
而不是.each()
。试试这个:What you've got looks fine but for one thing: using
$.each()
instead of.each()
. Try this:如果您不需要元素引用内部
doSomething
,您可以用这种稍微整洁的方式创建一个闭包:If you don't need the element reference inside
doSomething
, you can create a closure in this, slightly tidier way:人们在使用 ajax 和循环时遇到的主要“问题”是尝试重用稍后执行的函数内的迭代变量。例如,
出现此“陷阱”是因为所有
success
回调之间共享 1 个i
实例。在您的场景中,每个“迭代”级别都有一个
i
。所以这个陷阱不会击中你。The main "gotcha" people run into with ajax and loops is trying to reuse the iteration variable inside the function which executes later. For example
This "gotcha" occurs because there is 1 instance of
i
shared amongst all of thesuccess
callbacks.In your scenario though you have one
i
for every "iteration" level. So this gotcha won't hit you.由于
callback
是在.each()
函数中定义的,因此当您到达回调函数时,item
仍然在范围内。因此,如果doSomething()
从不使用self
,则无需传递它。您可以只引用item
:现在,如果回调是在
.each()
之外定义的,您必须按照自己的方式进行操作,传递item
到doSomething()
:Since
callback
is defined within the.each()
function,item
still is in scope by the time you get to your callback function. So, ifdoSomething()
never usesself
, you don't need to pass it. You can just referenceitem
:Now, if the callback were defined outside of
.each()
, you'd have to do it the way you have it, passingitem
todoSomething()
: