2016-06-08 36 views
0

我有一個函數被調用多次,它使用jQuery從API中獲取不同的JSON。添加JSON長度

我一直在試圖獲得該JSON的部分累計數。這是那種我有什麼:

getTheData(aBlah,bBlah,cBlah); 

getTheData(aStuff,bStuff,cStuff); 

function getTheData(aBlah,bBlah,cBlah){ 
    $.ajax({ 
    url: 'https://my.url.com/aBlah?bBlah?cBlah', 
    type:"GET", 
    data: { fields: "subdata" }, 
    dataType: "jsonp", 
    contentType:"application/json", 
    jsonpCallback: myCallback, 
    success: function(data){ 
     console.log(data.subdata.length); 
     'the rest of the code' 
    }); 
} 

我想獲得累計data.subdata.length的,但我不知道如何去得到它。

+2

您添加的代碼中存在語法錯誤。 – RRK

+0

您可以創建一個計數器作爲全局變量來存儲長度。將其初始化爲0,然後每個Ajax響應將其長度添加到計數器值中。說得通? –

回答

0

這是一個典型的用例closures

var closure = function(){ 

    var counter = 0; 

    function getTheData(aBlah,bBlah,cBlah){ 
    $.ajax({ 
    url: 'https://my.url.com/aBlah?bBlah?cBlah', 
    type:"GET", 
    data: { fields: "subdata" }, 
    dataType: "jsonp", 
    contentType:"application/json", 
    jsonpCallback: myCallback, 
    success: function(data){ 
     counter += data.subdata.length; 
     'the rest of the code' 
    }); 
} 

function getcount(){ 
    return counter; 
    } 

    return { 
     getTheData:getTheData, 
     getcount:getcount 
    } 
}; 

var myClosure= closure(); 
myClosure.getTheData(aBlah,bBlah,cBlah); 
myClosure.getTheData(aStuff,bStuff,cStuff); 

var count = myClosure.getcount(); 

這有助於控制計數器變量的作用域。因此,您可以執行以下操作:

var myClosure= closure(); 
myClosure.getTheData(aBlah,bBlah,cBlah); 
myClosure.getTheData(aStuff,bStuff,cStuff); 

var count = myClosure.getcount(); 

//counter in the new closure is zero 
var newClosure = closure(); 

newClosure.getTheData(aBlah,bBlah,cBlah); 
newClosure.getTheData(aStuff,bStuff,cStuff); 

var totallyNewCount = myClosure.getcount();