Rudi Starcevic
Rudi Starcevic

Reputation: 685

Coffeescript and markup based JS execution

From another thread here I found this great tutorial on markup based JS execution Garber-Irish solution:

http://www.viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution/.

I'm checking out how I can do parts of this in Coffeescript.

This works OK:

SITENAME.surveys.show = ->
  alert "Hello CoffeeScript"

Which renders out:

SITENAME.surveys.show = function() {
  return alert("Hello CoffeeScript");
};

This one is not so happy:

SITENAME.surveys.new = ->
  alert "Hello CoffeeScript"

SITENAME.surveys["new"] = function() {
  return alert("Hello CoffeeScript");
};

I'm new to Coffeescript and doing a codeschool.com course on it now. I guess the "new" keyword is special for coffeescript.

Is there any workaround for this?

Thanks!

Upvotes: 0

Views: 139

Answers (2)

mu is too short
mu is too short

Reputation: 434685

If you need to use new, you can use [] to define the function:

SITENAME.surveys['new'] = ->
  alert "Hello CoffeeScript"

and to call it:

SITENAME.surveys['new']()

Demo: http://jsfiddle.net/ambiguous/Y3qnt/

A quick review of your link suggests that you'll be accessing the function with something like:

controller = 'surveys'
action     = 'new'
SITENAME[controller][action]()

So it doesn't matter what the methods are called as you'll always be referring to them by their (string) name anyway.

Upvotes: 2

Robert Levy
Robert Levy

Reputation: 29073

new is special in JavaScript and CoffeeScript is aware of this so it's emitting code that will actually work even though it's bad practice to name methods using reserved keywords.

Upvotes: 2

Related Questions