Function Templates at Work

Ever since I’ve read Angus Croll’s post “Understanding javascript closures” I’ve been intrigued by the idea of creating function templates with closures, but until now it was never the suitable solution for my needs.

Last week the opportunity finally showed up…

I have a web application that does a lot of asynchronous work on the server, and uses socket.io to communicate the progress status to the client.

I was asked to create a REST API for this application.

The challenge was to keep the socket.io usage the same in the web app, while supressing the progress report in the REST API and sending JSON to the response on success or failure.

The web app needs socket.id to be available always in order to emit messages. The API needs the response stream available when  the process ends.

Passing these variables to all of the functions would be possible, but not very elegant.

The solution I chose was to encapsulate the communication function.

for the web app I created a function template that closes on the socket id, and for the API I created a function template that closes on the “res” variable.

The products of these templates were passed as parameters to the functions that do the actual work, and called whenever the progress status changed.

This is a simplified version of the result :

exports.startProcessAPI = function (req, res) {

var templateReportFunc = function (res)  {

return function (report) {

res.send(report);

}

},reportFunc = templateReportFunc(res);

_startProcess(reportFunc);

}

exports.startProcess = function (socket) {

var templateReportFunc = function (socket_id)  {

return function (report) {

io.sockets[socket_id].emit("report sent", report);

}

},reportFunc = templateReportFunc(socket.id);

_startProcess(reportFunc);

}

Summary

Creating function templates in order to “close” on variables that are useful further in the code’s execution can be very helpful, especially when there are separate execution paths that require different variables.

About these ads

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