Skip to content
March 26, 2008 / Ben Chun

Google Calendar and Javascript Closures

I’ve been working on a project to redevelop our school web site in WordPress MU. The idea is to continue and support what Patrick Delaney started years ago, with teachers and students blogging and making the web site a living part of the school instead of just a stiff brochure, or even (in the more modern conception) a utility. The idea is that this site and its blogs have the potential to be part of the teaching and learning that goes on at our school. So, high-minded Web 2.0 educational philosophy aside, the practical concern here is that we need to support about 100 teacher blogs, currently living in Manila. Hence, WordPress MU and a bunch of customization. It must be easy for teachers to use. It must look good. It must be powerful and able to integrate cleanly with other services.

In that frame of mind, as part of the WordPress implementation, we want to make it easy for individual teachers to display a Google calendar on their blog. No problem, the WPNG Calendar plugin is already written and has a widget implementation. (If you’ve never used WordPress, widgets are packaged bits of code that, when installed, offer users a drag-and-drop interface to add content “modules” to their blogs. Along with the theme and plugin architecture, it makes WordPress easy to develop for and work with.) We’re using widgets extensively to give teachers an easy way to lay out the content on their blogs, but still stick within a general design framework that gives us a consistent look.

The only problem with the calendar widget is that I wanted to be able to include more than one copy on a given blog. For example, on the main school blog we’d like to list out the sports calendar in a different space than other events. (You can temporarily have a look-see, if DreamHost is up today and we haven’t broken everything as we work on it.) I can also imagine teachers keeping different Google calendars for their different courses and wanting to display all of them on their blog. This particular widget was not set up with these use cases in mind. In fact, it was only a display widget for a calendar feed specified in a different option panel, and generally intended to have a dedicated page of its own. So the widget didn’t have many options of its own.

Fortunately, adapting it for multiple instances was easy (at first): store the feed URL in the widget options, add some UI to deal with that, tack on an ID numbers to each widget, make sure to use that ID when saving and loading the options, and add a little menu to the admin interface to let users specify how many of these thingies they want. Pretty stock widget development, all just glue code that I could copy by example. Easy, I thought, I’ll be done in no time. All I had left was hacking up the display code.

The output mechanism that actually gets the calendar data on the screen (after its been fetched and parsed) uses some JavaScript that does a clever little thing: when the page loads, the calendar has the event list div hidden and initially just shows a div with this loading animation:
loading_large.gif

Then we call the Google API and specify a callback function. (I parameterized this to allow the feed URL to be passed in from the saved options, instead of grabbed from a global variable as it was previously.) Once the data arrives, the callback function finds the event list div and loops over the calendar data, formatting and adding items to the list until it’s done as many as you told it to do. Finally, it hides the loading div and shows the list div.

Of course, I need to parametrize the div names since there can now be more than one of each. That’s easy enough to do when we build the page, and we already have individual IDs for each widget that we can tack on. But remember the callback function? Oh yeah, that. The problem is that the callback function needs to know the div name to do its magic. The callback a separate function. How can it know what div it should be looking for? Right now, the div name is hardcoded. So why not just pass it the div name? Because it’s Google’s code that invokes the callback when they get done fetching data. I can’t pass the div name through their code, because I can’t change their method signatures to give me an extra parameter. And, in fact, I don’t even want to do that. The code between where I kick off the request for the calendar data and get the callback doesn’t need to know anything about how or where I’m going to display the data.

So what’s the right way to handle this? Well, my callback function needs to have the div name available to it, without having it passed in. Global variables not only lose style points but also reduce to the same problem: which global variable am I looking for? One solution that would work is to hardcode a different function for each div, and pass the appropriate one in. But that’s very ugly. Not only would we be duplicating code, but we’d be duplicating it only to change one string in the whole function! As the meme goes, fail.

Think for a minute about how we’re passing the function as an argument. (This is the notion of first class functions.) Why not make a function that will build and return the function we want? This function is a higher-order function, and this is usually where programming really starts to “bake your noodle” as a friend of mine likes to say. The basic concept is straightforward: if you define a function inside another function, the inner function’s scope includes that of the outer function. That is, the inner function has access to all the variables in the outer function — that would be the first stop outside itself on the scope chain. This is the basic idea of closure.

Simple, right? Actually, it can be pretty confusing, especially without a clear understanding of how names are resolved into values and how scope changes with execution context.

You can’t solve the problem I solved today (cleanly) without understanding closures in JavaScript. And this is why it’s important for students to learn not only procedural and object-oriented programming styles, but also at least be exposed to a functional programming language. I don’t know that it’s necessary to do this in high school, but then again, why wait? I wonder if there’s a way to introduce this concept in the AP Computer Science course next year, perhaps after the AP exams are over. I feel like you can use any given programming language or environment to teach the concept of another language style or feature by having students implement one in the other. However, there are obviously going to be some combinations that work better than others. And there’s a real issue with cognitive load here. This stuff is like a logic puzzle sometimes, very rule-driven, with subtle ramifications and many questions to ask. For starters, how many times can a noodle get baked before it’s cooked?

13 Comments

Leave a Comment
  1. Joe / Apr 30 2008 5:18 am

    Great write up! I’m experiencing a similar issue right now with the Google Maps API, but more specifically, using the jMaps jQuery Plugin. I’m currently trying to get access to values from a callback function from Google in the global scope. After reading, your article, I think I finally “get” it. It sounds like I need to have a function that calls the function I was calling which has the callback function and in the “outermost” function declare the array I need to store the values in. I hope this works. Nice read indeed.

  2. Chris / May 13 2008 11:55 am

    Simple, right? Actually, it can be pretty confusing, especially without a clear understanding of how names are resolved into values and how scope changes with execution context.

    Yikes. Might I touch your foot on this one?
    Hat in hand, “Please, Sir, would you publish this as a WPMu plugin?”

    This is a core need for meme-sites. I Google App’d my domain hoping to get the group calendars sync’d nicely through RSS or iCal etc so that I could publish a master calendar but failed, miserably.

    Ben Chun, FTW!

  3. Ben Chun / May 13 2008 9:55 pm

    I’m considering trying to get this all reorganized for release. I would ideally like to contribute it back to the original project on Google Code, but so far I haven’t been able to get the “L1 Jockeys” (the owner of the project) to respond to my emails. They also seem to be ignoring the list of issues open on their project, which includes an enhancement request for multiple calendars and a suggestion from me to make the URLs a little easier to deal with. I’m not sure what the standard amount of time to wait for a response is. I know that I often ignore my own open source projects for years at a time.

    Anyway, I believe that you can take multiple Google calendars and display them on one embedded calendar. But of course you still have to use Google’s interface in that case.

  4. Ron / May 30 2008 1:38 pm

    I like the looks of what this can do but from an organizational standpoint. Would the NBA Make all entries for all teams on one calendar? No.
    I hope they respond and work with you on your project.

  5. jhaddadin / Jul 6 2008 10:04 am

    Hey,

    The calendar is up and running on my site, but I have many events in the calendar. Ideally, I’d like to display multiple calendars on the same page (concerts, club nights, sports events etc).

    As there any way you can share the modified code for multi calendar functionality?

  6. drumminhands / Dec 7 2008 3:01 pm

    I’m very interested to try your code for multiple calendar support. Is it posted anywhere, or would you be willing to email me the files?

    Thanks for the great write-up.

  7. Jim / Feb 5 2009 9:57 am

    Hi,
    I’ve just found your site and would like to know if you are now involved with the multiple calendar issue of WPNG or can you elaborate more on how to use multiple calendars with WPNG?

    We currently use several Google Calendars conbined to make up our school calendar.
    The teachers in charge of the various sports use Google to create a calendar as do several other departments within the school.
    All of these are then combined using the Google Embeddable Calendar Helper and displayed on the school website.
    Great, works really well!

    I’m now looking at using WordPressMU and offering it to staff and possibly students, with a blog to act as our intranet page which would display a combined Google Calendar.

    Many thanks for any help

  8. Courtney / Feb 26 2009 4:42 pm

    I would like to second jhaddadin, drumminhands and Jim. I have been trying to find an appropriate calendar plugin that will handle multiple (google) calendars/feeds, and just haven’t been successful. If you can provide any insights on how to make this work, it would be greatly appreciated.

    Thanks for your great post.

  9. Alesha / May 23 2009 9:36 pm

    Hey Ben! I got the link to your post from Google’s issue page for the wpng-calendar plugin. I’m trying to aggregate multiple Google calendars on a home page and list individual calendars on their respective pages for a website that I’m working on. I was very excited to see that you had tweaked the plugin for multiple calendar support. Would you be willing to share the code at all? Thank you so much. :)

  10. Adam / Jul 21 2009 12:16 pm

    I’m trying to do this exact same thing. Any chance of publishing a tutorial or posting your working files?

  11. thedairyshow / Jan 20 2010 10:30 am

    Hi Ben,

    Can I get a copy of the code to run multiple calendars?

    Thanks!

Trackbacks

  1. How to Teach CS « And Yet It Moves
  2. WordPress MU « And Yet It Moves

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: