咖啡脚本中的 switch case 语句 [英] Switch case statement in coffee script

查看:36
本文介绍了咖啡脚本中的 switch case 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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 中:

There are two forms of switch in CoffeeScript:

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

和:

switch
    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 target.is '#black' then new App.BlackView
  else null

如果 undefinedview 的可接受值,您可以省略 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(target.is '#black')
    null

view = viewFor target

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

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

这篇关于咖啡脚本中的 switch case 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆