Javascript’s “this” makes OO callbacks a pain

One thing I’ve learned since doing a lot of Javascript coding is that mixing the callback style of coding and OO is a bit of a pain.

When issuing a callback that you want to be a method on this rather than a plain function, you need to copy this into a variable so that it can be a regular closure variable. Here’s a typical example (slightly edited) from haraka:

var self = this;
hmail.on('ready', function() { self.load_queue_files(param1, param2) });

Whereas if you weren’t using OO, you could use a regular function (assuming no params are required):

hmail.on('ready', load_queue_files);

Now I could create some sort of sugar for this, so I could do:

hmail.on('ready', lambdoo(this, "load_queue_files", param1, param2))

However it’s not really that much nicer, and I worry it would confuse the V8 optimizer (though this is a case of my brain doing premature optimisation). This can be implemented as follows:

function lambdoo (object, method) {
var args = [];
for (var i=2; i < arguments.length; i++) {
return function () { object[method].apply(object, args) }

Now that doesn’t deal with any params passed to the outer function (like “err”), but that can be doable too with a bit more usage of “arguments”.

What’s probably needed is some pre-parser sugar that can take something like this:

hmail.on('ready', lambdoo this.load_queue_files(param1, param2)) // just DWIM

I call it “lambdoo” after “lambda” but with an OO context.

I guess this is the kind of thing solved by coffeescript, but I haven’t looked into it too deeply.


One thought on “Javascript’s “this” makes OO callbacks a pain

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s