【发布时间】:2015-12-16 19:07:58
【问题描述】:
我的程序有以下 $.each 循环:
var uiData = {};
$.each(disciplines, function(key, discipline) {
var cacheKey = getCacheKey(discipline, from, to, type);
// http://www.2ality.com/2011/02/javascript-variable-scoping-and-its.html
// http://speakingjs.com/es5/ch16.html#inadvertently_sharing_environments
success = (function(_d) {
var __d = _d;
return function(data) {
if (!(data instanceof Graph)) {
data = new Graph(data['vertices'], data['edges']);
graphs[cacheKey] = data;
}
uiData[__d] = data.getVertices().length;
graph.merge(data, mergeRecursiveInto, mergeRecursiveInto);
};
}(discipline));
if (cacheKey in graphs) {
// timeout is necessary, to simulate an ajax-call to give the browser time to show the loading - dialog
setTimeout(function () {
barrier.waitOn(success)(graphs[cacheKey])
}, 50);
} else {
$.ajax({
type : "POST",
url : jsonUrls[type],
data : {
d : [ discipline ],
from : yearFrom,
to : yearTo
},
success: barrier.waitOn(success)
});
}
});
我期望的是,对于每次迭代,都应该是使用discipline 生成的单独成功函数。我阅读了提到的两个链接并认为我理解它,但我的调试器说了别的。 IIFE 不会对该学科进行快照。
那么问题是什么,我错过了什么?
【问题讨论】:
-
你还没有宣布成功,所以它被覆盖了。
-
success在哪里定义?父作用域中是否有var success?否则,success将被定义为一个全局变量,在每次迭代时都会被覆盖。如果确实如此,在success =前面放置var将解决此问题。 -
你说的太对了。这是一周内第二次让我站起来。不,我忘记了:(。
-
好的,有一个问题。为什么每个人都只将答案发布为评论,而不是真正的答案?第二个问题是在哪里发生的,这有什么特别的吗?
标签: javascript jquery iife