2013-03-18 33 views
1

我一直在面對一個問題,當我試圖通過javascript v3 api將多個事件添加到Google日曆時。Google日曆javascript api - 添加多個事件

我有一個數組,其條目是這樣的事件:

newEvent = { 
    "summary": response[i].name+" BDay!!", 
    "start": { 
     "dateTime": date 
    }, 
    "end": { 
     "dateTime": date 
    } 
    }; 

    events[i]=newEvent; 

之後,我做出谷歌日曆API的調用,以添加事件:

var request; 
for(var j = 0; j<events.length; j++) { 

    console.log(events[j]); 

    request = gapi.client.calendar.events.insert({ 
    'calendarId': calendarId, 
    'resource': events[j] 
    }); 
    request.execute(function(resp) { 
    console.log(resp); 
}); 
} 

然而,事實證明,所有的事件都放在日曆中的相同日期(實際上是數組事件[]中的最後一個日期)。我相信這可能是因爲請求是回調函數,但我不確定。

將不勝感激的幫助!

回答

3

events[j]正在for循環的每次迭代中被反彈。嘗試使用匿名函數綁定到正確的事件:

var request; 
for(var j = 0; j<events.length; j++) { 

    console.log(events[j]); 

    request = function(resource) { // Function that returns a request. 
    return gapi.client.calendar.events.insert({ 
     'calendarId': calendarId, 
     'resource': resource 
    }); 
    }(events[j]); // Bind to the current event. 
    request.execute(function(resp) { 
    console.log(resp); 
    }); 
} 

請參見以下問題對JavaScript數組和封鎖的詳細信息:JavaScript closure inside loops – simple practical example

這裏是代碼的更容易閱讀的版本之上將所有處理移動到一個函數中:

var makeRequest = function(resource) { 
    console.log(resource); 
    var request = gapi.client.calendar.events.insert({ 
    'calendarId': calendarId, 
    'resource': resource 
    }); 
    request.execute(function(resp) { 
    console.log(resp); 
    }); 
}; 

for(var j = 0; j<events.length; j++) { 
    makeRequest(events[j]); 
} 
+0

謝謝,它至少幫助瞭解更多關於閉包和變量邊界的javascript。然而,我只是在循環中綁定了事件[j]之後才解決了這個問題,也因爲我沒有爲每個創建的事件創建一個新的日期,而是我每次只更新同一個變量,並且出於某種原因沒有按預期工作。無論如何,再次感謝! – gpestana 2013-03-21 22:25:06

3

如果要一次插入多個事件,則應使用批處理。

var batch = gapi.client.newBatch(); 
batch.add(gapi.client.calendar.events.insert({ 
    'calendarId': 'primary', 
    'resource': events[0] 
})); 
batch.add(gapi.client.calendar.events.insert({ 
    'calendarId': 'primary', 
    'resource': events[1] 
})); 
batch.add(gapi.client.calendar.events.insert({ 
    'calendarId': 'primary', 
    'resource': events[2] 
})); 
      ...... 

batch.then(function(){ 
    console.log('all jobs done!!!') 
}); 
相關問題