2015-09-19 115 views
1

我的程序有以下$。每個循環:

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不會快照這門學科。 那麼問題是什麼,我錯過了什麼?

+0

您尚未聲明成功,因此被覆蓋。 –

+1

「成功」的定義在哪裏?父範圍中是否有'var success'?否則,'success'將被定義爲一個全局變量,每次迭代都會被覆蓋。如果確實如此,在'success ='前放置一個'var'將解決這個問題。 –

+0

你是如此的正確。這是一週以來的第二次,這讓我跌倒了。不,我忘了它:(。 – spaeg

回答

0

像Daniel A. White和musically_ut說的,我忘了定義成功。

var success = ...解決了這個問題。

感謝所有。