CoffeeScript 中的 Switch case 语句

60

我有几个不同的按钮调用同一个函数,我想将它们包装在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?

无论如何,这并不适合使用switch语句(hasClass vs is)。 - user2864740
2个回答

117

CoffeeScript 中有两种 switch 的形式:

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

并且:

switch
    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

如果对于viewundefined是一个可接受的值,您可以省略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

给你的代码逻辑命名(即将其封装在函数中)通常有助于澄清您的代码。


9
请注意,then 只能在单行赋值中使用。如果您将代码写在 then 下面,就不要放置 then,否则会在编译过程中失败。 - Vadorequest

22

除了接受的答案中提到的细节之外,CoffeeScript中的switch语句还支持,来提供多个匹配结果:

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

或者(如果您的语句有多行):

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

1
我认为这里不应该使用or - 它会创建一个case (val1 || val2):语句 - 即在val1val2上运行布尔操作 - 这不是我在这里期望的。然而,逗号可以解决这个问题。 - Voy
@Voy:你是对的 - or 操作符不能产生期望的结果。回答已更新。 - larsmoa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接