在咖啡脚本中切换案例陈述

use*_*731 55 if-statement switch-statement coffeescript

我有一些不同的按钮调用相同的功能,我希望将它们包装在一个switch语句中,而不是使用一堆其他条件.任何帮助都会很棒!!!

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?
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 112

switchCoffeeScript 有两种形式:

switch expr
    when expr1 then ...
    when expr2 then ...
    ...
    else ...
Run Code Online (Sandbox Code Playgroud)

和:

switch
    when expr1 then ...
    when expr2 then ...
    ...
    else ...
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

你可以省略else nullif undefined是可接受的值view.您还可以将逻辑包装在(显式)函数中:

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
Run Code Online (Sandbox Code Playgroud)

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

  • 请注意,`then`必须**仅用于单行分配.如果您在下面编写代码,请不要输入`then`,否则在编译期间会失败. (8认同)

lar*_*moa 21

除了在细节上公认的答案,switch在CoffeeScript中的语句还支持,提供多种比赛结果:

switch someVar
    when val3, val4 then ...
    else ...
Run Code Online (Sandbox Code Playgroud)

或(如果您的陈述有多行):

switch someVar
    when val3, val4
        ...
    else
        ...
Run Code Online (Sandbox Code Playgroud)