user1981569
user1981569

Reputation:

javascript jQuery variable scope

Thanks in advance. I'm making a website for a service I run with my partner called Laughter Yoga Dublin. I've come across a problem that's got me stuck. It looks like lots of code below but my question pertains mainly (I think) to the first and last few lines.

The first five lines are variable declarations as you can see. Those lines are followed by a jQuery function beginning ($.getJSON etc...) in which those variables are processed. And that function ends just before the last few lines of code given below.

My question is: how come the lines at the end of the code (console.log etc...) are showing that the variables' values are uninfluenced by the preceding function? I'm the first to admit that I'm a baby with this programming stuff but I thought that since I'd declared the variables outside the function, their values could be changed from within the function. Have I got that wrong? I'm finding it a bit hard to understand, and my own (limited) experience with this seems to contradict the effects of the bit of code below.

I'm willing to research and learn but I'd really appreciate even a nudge in the right direction with this problem.

Thanks again, Niall, Dublin, Ireland.

    var events = []
    var theBitImInterestedIn
    var prettyDate;
    var nextEventString;
    var JSONurl = 'https://www.google.com/calendar/feeds/avmknaehgjre8qjqhbi22fn8mo%40group.calendar.google.com/public/basic?alt=json&orderby=starttime&max-results=20&singleevents=true&sortorder=ascending&futureevents=true';     
    $.getJSON(JSONurl ,function(data){
    theBitImInterestedIn = data.feed.entry;
    $.each(theBitImInterestedIn, function(key, val){
        var event = {};
        var Content = val.content.$t;
        var weekDayNumber, weekDay = '', Days=['Mon','Tue','Wed','Thu', 'Fri', 'Sat', 'Sun'];
        var monthNumber, monthOfTheEvent = '', Months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
        var venue = theBitImInterestedIn[0].content.$t
        venueBegin = venue.indexOf('Where');
        venueMod = venue.substring(venueBegin);
        venueEnd = venue.indexOf('<br') -2;
        venue = venueMod.substring(7, venueEnd);
        $.each(Days, function(key, val){
        if (Content.match(Days[key])){
            weekDay = val;
            weekDayNumber = key + 1;
        }
        })
        $.each(Months, function(key, val){
        if (Content.match(Months[key])){
            monthOfTheEvent = val;
            monthNumber = key + 1;
        }
        })
        var actualDay = Content.match(/\d+/)[0];
        var year = Content.match(/\d+/g)[1];
        event.Title = 'Laughter Yoga';
        var tempDate = monthNumber  + '/' + actualDay + '/' + year;
        var prettyDate = weekDay + ' ' + actualDay + ' ' + monthOfTheEvent + ' ' + year;
        event.Venue = venue;
        event.PrettyDate = prettyDate;
        event.Date = new Date(tempDate);
        events.push(event);
    })
    nextEventString = 'Next class: ' + events[0].PrettyDate + ' at ' + events[0].Venue;
    //$('p').html(nextClassString).appendTo('#next-class');
    });
console.log(events);     //these result in an empty [] and undefined 
console.log(theBitImInterestedIn)
console.log(prettyDate)
console.log(nextEventString)

Upvotes: 2

Views: 90

Answers (1)

Robbert
Robbert

Reputation: 6582

As mentioned, getJSON is asynchronous. In order for console.log to do anything with the changed variables, you would need to call them in a function after the asynchronous call.

var events = []
var theBitImInterestedIn
var prettyDate;
var nextEventString;

function callJSON() {
  var JSONurl = 'https://www.google.com/calendar/feeds/avmknaehgjre8qjqhbi22fn8mo%40group.calendar.google.com/public/basic?alt=json&orderby=starttime&max-results=20&singleevents=true&sortorder=ascending&futureevents=true';     
  $.getJSON(JSONurl ,function(data){

      ...

      ///////////////////////////////////////////////////////////////
      // call to show console log
      ///////////////////////////////////////////////////////////////
      logConsole()

  });

}

function logConsole() {
  console.log(events);     //these result in an empty [] and undefined 
  console.log(theBitImInterestedIn)
  console.log(prettyDate)
  console.log(nextEventString)
}

Upvotes: 1

Related Questions