Tag Archives: JavaScript

JavaScript & Python Closures

After a hard day of climbing in the canyon my fellow climbing/coder friend Tim started to tell me about a feature of JavaScript he had just started to use called Closures. Even though I have written thousands of lines of JavaScript I had never heard of Closures. As a self proclaimed eternal student I was intrigued with what he was telling me.

Turns out that Closures are generally considered to be JavaScripts most advanced and useful feature, and hence, is worthy of a blog post :-). As a C++ coder I like to think of Closures as a method with a privately malloc’d stack that is persistent across multiple invocations. As a Python coder I like to think of Closures as a method object with a preserved variable environment. Regardless of how you want to think about them, Closures allow us to redefine how we approach coding up methods.

Take the following simple JS example. Here, we are creating a very simple incrementer. The method inc() takes a starting value and returns a method that simply adds one to the start value (but not until its actually executed in the loop below).

function inc(start){
	var i = start;
	return function() { i = i + 1; document.write(i); }
}

addOne = inc(0)
for (i = 0; i < 10; ++i){
	addOne();
}
// prints 12345678910

I’m probably just super geeky but I find this feature of the language very cool. Turns out we can also do the same thing with Python.

#Works with Python 3.x only
def inc(start):
    y = start
    def adder():
        nonlocal y
        y += 1
        print y
        return y
    return adder
 
addOne = inc(0)
x = 0
for x in range(10):
    addOne()
#prints 12345678910

The ramifications of Closures to popular programming languages are still in its infancy even though the concept has been around for decades (adding them to Java has been a debate for years). It will be extremely interesting to see how the wide spread adoption of Closures will ultimately impact our coding habits in the near future.

Web Apps – The More Custom The Better

I’m a big fan of the WebKit Qt framework integration. It will without a doubt change the face of web based content delivery over the next few decades (previous post). By far the most powerful aspect of this integration is the ability to create custom JavaScript APIs for hybrid web based applications in a browser.

Put simply, browsers can customize the functionally they offer by implementing features into the browser that can be accessed by web content via JavaScript.  Web apps that exercise this functionally must be written to do so, making them “custom” web apps.  Meaning that an app written to utilize features defined in certain browsers will not work without modification in Explorer, Firefox, or Chrome. For example, when GE integrates a web browser into their next generation refrigerators, it would be beneficial to expose an API that allowed an app to check the inside temperature or level of the ice tray.

I’ve been in many debates with other engineers about this option.  Not one engineer has ever agreed with me right off the bat.  Most oppose doing it as it limits were an app can be run and defeats the purpose of web content.  The “purpose” being mass distribution and play-ability on many different standardize browsers.  Most don’t understand why you’d create a web app that can only be executed on a limited number of browsers.  Many also argue that it burdens app developers with having to learn yet another JavaScript API.  Regardless of the objection, this option is widely opposed and not fully understood by most engineers.

The engineering objections are easy to argue against.  First of all, there is no such thing as a standardized browser.  Despite standardization efforts from W3C,  the JavaScript language is a mess.  The big three, IE, Firefox, and Chrome all use a different JavaScript engine and have varying degrees of standardization completeness (some even have features not covered by W3C).  If you want your website to work across the big 3 you already have to add additional code.  I know its a stretch, but this is already a form of web app customization.

The real value add of customized web apps is from a business perspective.  I come from the embedded device world where the number of units sold is the driving factor (compared to the number of hits). By forcing apps to write to your API you are ensuring a certain level of stickiness.  It can be a competitive advantage to limit the devices an app can run on by exposing custom functionality through the browser.  GE won’t want its ice tray level app to run on LG with no modification for the same reason Apple does’t want its apps to run on Android without a rewrite.

Adding a custom JavaScript API to your Qt WebKit browser is easy.  Nokia has a great blog post on its forum here. To illustrate its simplicity I’ve included my own snippet below.

Any C++ object can be complied into the browser and exposed to the JS engine.

class FakeObject
{
public:
	FakeObject(QObject *parent);
public slots:
	posterInternalCommand(QString command, QString data);
signals:
	fakeSignal();
}

FakeObject::FakeObject(QObject *parent)
{

}

bool FakeObject::postInternalCommand(QString command, QString data)
{
	// Do something with data
	return True;
}

FakeObject::emitSignalTest()
{
	emit fakeSignal();
}

After instantiation the object is exposed to the JS engine using a QWebFrame method.

FakeObject* m_pfake = new FakeObject(webView);
webView->page()->mainFrame()->addToJavaScriptWindowObject(QString("fake"),m_pFake);

The exposed object can now be acted on via JavaScript. Public slots are methods that can be called directly from JS. Signals can also be connected to local JS methods making for more asynchronous functionality.

b = window.fake.postInternalCommand("fakeCommand", "fakeData")

function fakeCallBack(){
	x = x + 1
}

window.fake.fakeSignal.connect(fakeCallBack)

Red Hot Pawn Gadget

I love online chess. I typically play anywhere from 10-15 games at any given time. Red Hot Pawn has a default move timeout of once every 3 days, so games can sometimes last over a month. What I hate about online chess is not knowing if its your turn without loging in or signing up to receive a bunch of email notifications.

My solution was to write a Windows Sidebar Gadget that periodically checks for pending games. When you login to your RHP account using Microsoft Internet Explorer the Gadget then uses AJAX to get the number of games where its your move. This allows me to do whatever I want on my desktop and know exactly when I can switch back to the browser and play some chess 🙂

Many of the settings are configurable in the widgets flyout panel. Basic stuff like the check interval, a count down timer, and the name size are adjustable. Oh, and during December the Red Pawn wears a Santa hat!

The code is HTML/JavaScript and can be forked on GitHub here. As a warning, this tool was very much a rapid prototype and I cared more about getting it to work fast then optimization and readability. If you want to download it and use it you can do so here.