gpestana gpestana - 3 months ago 62
Javascript Question

Google Calendar javascript api - Add multiple events

I've been facing a problem when I'm trying to add multiple events to a Google Calendar via javascript v3 api.

I have an array which entries are events like these:


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

events[i]=newEvent;



After, I make a call to Google Calendar api in order to add the events:

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);
});
}


However, it turns out that all the events are placed in the same date into the calendar(which actually is the last date in array events[]). I believe that it could be because the requests are callback functions, but I'm not sure.

Would appreciate the help!

Answer

events[j] is being rebound on each iteration of the for loop. Try using an anonymous function to bind to the correct event:

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);
  });
}

See the following question for more details on JavaScript arrays and closures: Javascript closure inside loops - simple practical example

Here is an easier-to-read version of the code above that moves all the processing into a function:

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]);
}