user992731 user992731 - 1 year ago 165
CoffeeScript Question

Switch case statement in coffee script

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!!!

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

openOverlay: (e) ->

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 '#black' then new App.BlackView

# Open the view
App.router.overlays.add view: view if view?

Answer Source

There are two forms of switch in CoffeeScript:

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


    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 '#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( '#black')

view = viewFor target

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download