Question

How to I do this in CoffeeScript:

window.onload = function() {
  test.init();
};

var test = (function() {
  var num = 1;

  var pub = function() {
    document.body.innerHTML = num;
  };

  return {
    init: function() {
      pub();
    }
  }

}());

JSFiddle

Was it helpful?

Solution

This translates quite one-by-one:

window.onload = ->
  test.init()

test = do ->
  num = 1
  pub = ->
    document.body.innerHTML = num;

  init: ->
    pub()

(compile)

However, you might shorten it (and the js similarly) to just

test = do ->
  num = 1
  init: ->
    document.body.innerHTML = num;
window.onload = test.init

(compile)

Optionally, you can insert empty parenthesis (no parameters) before every ->.

OTHER TIPS

It looks like this should do the trick:

window.onload = -> test.init()

test = do ->
  num = 1
  pub = -> document.body.innerHTML = num
  init: -> pub()

Or this, if you explicitly don't want the functions to return anything:

window.onload = ->
  test.init()
  return

test = do ->
  num = 1
  pub = ->
    document.body.innerHTML = num
    return
  init: ->
    pub()
    return

js-2-coffee is a really handy website for this kind of thing in the future

It gives the following coffeescript when you paste in your javascript

window.onload = ->
  test.init()
  return

test = (->
  num = 1
  pub = ->
    document.body.innerHTML = num
    return

  init: ->
    pub()
    return
())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top