if-statement - CoffeeScript 中的 switch case 语句

标签 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 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有两种形式在 CoffeeScript 中:

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

如果 undefinedview 可接受的值,则可以省略 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

为您的逻辑命名(即将其包装在函数中)通常对于阐明您的代码很有用。

关于if-statement - CoffeeScript 中的 switch case 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23046257/

相关文章:

php mysql 查询循环if语句

ruby-on-rails - 根据我所处的 View 制作 if 条件 (Rails 4)

javascript - 调度程序未在 Jest 单元测试中注册回调

C# 遍历 switch 的案例

if-statement - 是否围绕不良做法切换 if 语句?

Java - 为什么当用户输入不需要的内容时不显示错误对话框?

C++ 收到整数类型的 char,导致 switch case 出错

go - 在 Go 中根据字符串选择正确的导入

javascript - Three.js getTangent on curve 应该在曲线上移动时正确旋转我的对象

jquery - 如何使用 jQuery 将值传递到 coffescript ActionCable