HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Passing Context in CoffeeScript

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
contextpassingcoffeescript

Problem

I'm trying to migrate from JavaScript to CoffeeScript. However I'm not sure about the best way to optimize the code generated by js2coffee.

Below is the original JavaScript source :

var async = require('async');

var context = {};
context.settings = require('./settings');

async.series([setupDb, setupApp, listen], ready);

function setupDb(callback)
{
  context.db = require('./db.js');
  context.db.init(context, callback);
}

function setupApp(callback)
{
  context.app = require('./app.js');
  context.app.init(context, callback);
}

// Ready to roll - start listening for connections
function listen(callback)
{
  context.app.listen(context.settings.http.port);
  callback(null);
}

function ready(err)
{
  if (err)
  {
    throw err;
  }
  console.log("Ready and listening at http://localhost:" + context.settings.http.port);
}


And below is the generated CoffeeScript :

setupDb = (callback) ->

  # Create our database object
  context.db = require("./db")

  # Set up the database connection, create context.db.posts object
  context.db.init context, callback
setupApp = (callback) ->

  # Create the Express app object and load our routes
  context.app = require("./app")
  context.app.init context, callback

# Ready to roll - start listening for connections
listen = (callback) ->
  context.app.listen context.settings.http.port
  callback null
ready = (err) ->
  throw err  if err
  console.log "Ready and listening at http://localhost:" + context.settings.http.port
async = require("async")
context = {}
context.settings = require("./settings")
async.series [setupDb, setupApp, listen], ready


Now, I'm not sure if the context variable is required in CoffeeScript. In the JavaScript source its function is to share the common set of setting across the various components of the application such as database and the settings. Will a proper use of the => operator in CoffeeScript help ? If yes how ?

Solution

The CoffeeScript looks fine to me. You'll still need the context var just as in plain JS, because you're not dealing with this. If you were, you could maybe use the fat arrow to preserve the this context, but even so it'd require some refactoring, and end up very different from the original JS.

CoffeeScript's fat arrow is basically meant to be used where you'd otherwise do the var that = this; trick in JavaScript. But since you're not doing such things in your JavaScript, there's no need or opportunity for it in the CoffeeScript either.

Context

StackExchange Code Review Q#23076, answer score: 2

Revisions (0)

No revisions yet.