60

I have a few different buttons that are calling the same function and I would like to have them wrapped in a switch statement instead of using a bunch of else if conditions. Any help would be great!!!

events:
"click .red, .blue, #black, #yellow" : "openOverlay"

openOverlay: (e) ->
  e.preventDefault()
  e.stopPropagation()

target = $(e.currentTarget)

# the view should be opened
view = 
  if target.hasClass 'red' then new App.RedView
  else if target.hasClass 'blue' then new App.BlueView
  else if target.is '#black' then new App.BlackView
  else
    null

# Open the view
App.router.overlays.add view: view if view?
BC.
  • 24,298
  • 12
  • 47
  • 62
user992731
  • 3,400
  • 9
  • 53
  • 83

2 Answers2

117

There are two forms of switch in CoffeeScript:

switch expr
    when expr1 then ...
    when expr2 then ...
    ...
    else ...

and:

switch
    when expr1 then ...
    when expr2 then ...
    ...
    else ...

The second form might help you:

view = switch
  when target.hasClass 'red' then new App.RedView
  when target.hasClass 'blue' then new App.BlueView
  when target.is '#black' then new App.BlackView
  else null

You could leave out the else null if undefined is an acceptable value for view. You could also wrap the logic in an (explicit) function:

viewFor = (target) ->
    # There are lots of ways to do this...
    return new App.RedView   if(target.hasClass 'red')
    return new App.BlueView  if(target.hasClass 'blue')
    return new App.BlackView if(target.is '#black')
    null

view = viewFor target

Giving your logic a name (i.e. wrapping it in a function) is often useful for clarifying your code.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • 9
    Beware that the `then` must **only** be used in one-line assignation. Don't put a `then` if you write your code below or it will fail during the compilation. – Vadorequest Mar 04 '16 at 14:57
22

In addition to the details in the accepted answer, switch statements in CoffeeScript also supports , to provide multiple match results:

switch someVar
    when val3, val4 then ...
    else ...

or (if your statements has multiple lines):

switch someVar
    when val3, val4
        ...
    else
        ...
Community
  • 1
  • 1
larsmoa
  • 12,604
  • 8
  • 62
  • 85
  • 1
    I don't think`or` is right here - it will create `case (val1 || val2):` statement - ie. running a boolean operation on `val1` and `val2`- which is not what I'd be expecting here. The `,` does the trick though. – Voy May 17 '17 at 17:26
  • @Voy: you are right - `or` doesn't produce the desired result. Answer updated – larsmoa May 18 '17 at 20:04