Sunday, February 1, 2015

Requiring Functions

The grand plan is to update Episode.Next to use Web Workers to do all the background synching with TheTVDB and App Engine. It should solve the responsiveness issues that it has. Before I jumped into it, it seemed like it was time to solve the long running desire to use RequireJS and move all the JS out of the main window context. This took... a while.

The big thing I had to wrap my head around was the meaning of this. I had all these event handling methods being used by Episode.Next and was setting them as click handlers - $(…).click(episodeNext.clickHandler). So when the method clickHandler is called, what is the meaning of this? All my Java-based experience told me that it should be the EpisodeNext Object that contained the function, but that’s just not the way this language works. EpisodeNext isn’t a Class, it’s just a hash, and so clickHandler isn’t a method on the class, it’s just a variable that points to a function. So what does this mean? It’s the object that called the function (not the class that defines the method).

Once I got my head all wrapped around this than the call “simply" becomes $(…).click(function (event) { episodeNext.clickHandler(event); }). The way I actually got my head on straight was to realize it was basically the same as usual a weak Perl object without blessing it with a class. The result is that I have anonymous functions littered throughout my beautiful code so that I can pretend I’m working in an object-oriented language because the JS programmers of the world decided that it’s the right way to do this.