view raw
Dave Dave - 8 months ago 32
CoffeeScript Question

Getting "reserved word 'function’" when trying to define coffee script function

I have this coffee script

@open_login_dialog = () ->
opt = {
autoOpen: false,
modal: true,
width: 'auto',
focus: function(e) ->
$(this).dialog('option', 'width', $("#loginBox").width())

Rails is reporting the cryptic error, “SyntaxError: [stdin]:184:12: reserved word 'function’”. It doesn’t tell me a line, but when I comment out the “focus:function” part everything works, which leads me to believe that’s the culprit. How do I write the above so that it plays nicely with coffee script?


As per @muistooshort's comment, You need to use coffeescript function syntax, which replaces function(a,b,c) with (a,b,c) ->

Secondly, you need to continue using : for assignment inside an object.

I would also suggest brushing up a little on coffeescript. This is my favourite resource on the language. A linter would also help to catch these basic syntax errors.

Your code can be further cleaned up:

@open_login_dialog = ->
  opt = 
    autoOpen: false
    modal: true
    width: 'auto'
    focus: -> 
      $(this).dialog 'option', 'width', $('#loginBox').width()


  1. If you don't expect any parameters, you can leave out the () from the function definition and just use the arrow ->.

  2. You don't need {} brackets to define an object

  3. When defining an object over multiple lines, there is no need for trailing commas
  4. You aren't using the eventObject e in the focus listener, so that can be left out too.
  5. Parenthesis are optional when calling functions and passing them parameters.