gpt4 book ai didi

javascript - 在循环中定义ajax回调覆盖

转载 作者:行者123 更新时间:2023-11-28 01:30:22 26 4
gpt4 key购买 nike

我制作了一个ajax预过滤器,在执行原始回调之前等待模态窗口消失,效果很好......

$.ajaxPrefilter ( options, originalOptions, jqXHR )->

# perhaps these could be defined in a loop from an array
jqXHROriginaldone = jqXHR.done
jqXHROriginalfail = jqXHR.fail

jqXHR.done = ->
args = arguments
myfunc = ->
$(listener).off "ajax.progress.dismissed", myfunc
jqXHROriginaldone args
$(listener).on "ajax.progress.dismissed", myfunc

jqXHR.fail = ->
args = arguments
myfunc = ->
$(listener).off "ajax.progress.dismissed", myfunc
jqXHROriginalfail args
$(listener).on "ajax.progress.dismissed", myfunc

我不喜欢为每种状态类型重复我的代码...我想进行更改,以便可以循环设置所有状态(完成/失败/等...)...

$.ajaxPrefilter ( options, originalOptions, jqXHR )->

# object to store original callbacks for later use
originals = {}

for status in ['done','fail']

originals[status] = jqXHR[status]
jqXHR[status] = ->
args = arguments
myfunc = ->
$(listener).off "ajax.progress.dismissed", myfunc
originals[status] args
$(listener).on "ajax.progress.dismissed", myfunc

对我来说,它看起来像是等效代码,但它失败了,并且在控制台中没有显示任何错误,只是不运行回调函数。

为什么我的循环方法有效?

最佳答案

在循环内构建函数会引发危险信号。您的 status 变量在实际使用之前不会被评估。如果我们查看您的 myfunc:

myfunc = ->
$(listener).off "ajax.progress.dismissed", myfunc
originals[status] args

我们将看到一个 status 引用,在调用 myfunc 之前不会对其进行求值。发生这种情况时,status 将始终为 'fail',因为这就是循环完成时的 status

JavaScript 中通常的解决方案是使用 SIF 作为循环体:

for(i = 0; i < n; ++i)
(function(i) {
//...
})(i);

但是在 CoffeeScript 中有 do :

When using a JavaScript loop to generate functions, it's common to insert a closure wrapper in order to ensure that loop variables are closed over, and all the generated functions don't just share the final values. CoffeeScript provides the do keyword, which immediately invokes a passed function, forwarding any arguments.

所以像这样的东西应该效果更好:

for status in ['done','fail']
do (status) ->
# What you have now...

关于javascript - 在循环中定义ajax回调覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22193463/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com