If statement coffee脚本中的Switch case语句

If statement coffee脚本中的Switch case语句,if-statement,coffeescript,switch-statement,If Statement,Coffeescript,Switch Statement,我有几个不同的按钮,它们调用相同的函数,我希望将它们包装在switch语句中,而不是使用一堆else if条件。任何帮助都将是伟大的 events: "click .red, .blue, #black, #yellow" : "openOverlay" openOverlay: (e) -> e.preventDefault() e.stopPropagation() target = $(e.currentTarget) # the view should be open

我有几个不同的按钮,它们调用相同的函数,我希望将它们包装在switch语句中,而不是使用一堆else if条件。任何帮助都将是伟大的

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?
CoffeeScript中有两种形式的脚本:

switch expr
    when expr1 then ...
    when expr2 then ...
    ...
    else ...
以及:

第二种形式可能会帮助您:

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
如果
未定义
视图
的可接受值,则可以省去
else null
。您还可以将逻辑封装在(显式)函数中:

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

为逻辑命名(即将其包装在函数中)通常有助于澄清代码。

除了CoffeeScript中的
开关
语句中的详细信息外,还支持
以提供多个匹配结果:

switch someVar
    when val3, val4 then ...
    else ...
或者(如果您的语句有多行):


无论如何,它不适合switch语句(hasClass vs is)。请注意,
then
只能在一行赋值中使用。如果你在下面写代码,那么不要把
放进去,否则编译过程中就会失败。我不认为
就在这里-它会创建
案例(val1 | | val2):
语句-即在
val1
val2
上运行布尔运算-这不是我在这里期望的。
确实起到了作用。@Voy:你说得对-
没有产生想要的结果。最新答案
switch someVar
    when val3, val4 then ...
    else ...
switch someVar
    when val3, val4
        ...
    else
        ...