Tag Archives: Closures

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) {



},reportFunc = templateReportFunc(res);



exports.startProcess = function (socket) {

var templateReportFunc = function (socket_id)  {

return function (report) {

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


},reportFunc = templateReportFunc(socket.id);




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.