在咖啡脚本中切换case语句 [英] Switch case statement in coffee script

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

问题描述

我有几个不同的按钮,调用相同的功能,我想让他们包装在switch语句,而不是使用一堆else if条件。任何帮助将是伟大的!

 事件:
点击.red,.blue,#black, yellow:openOverlay

openOverlay:(e) - >
e.preventDefault()
e.stopPropagation()

target = $(e.currentTarget)

#视图应打开
view =
if target.hasClass'red'then new App.RedView
else if target.hasClass'blue'then new App.BlueView
else if target.is'#black'那么新的App.BlackView
else
null

#打开视图
App.router.overlays.add视图:view if view?

解决方案

switch

  switch expr 
当expr1时...
当expr2时...
...
else ...

和:

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

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

  view = switch 
当target.hasClass'red'然后new App.RedView
当target.hasClass'blue'然后新App.BlueView
当target.is'#black'然后新App.BlackView
else null

你可以省略 else null 如果未定义视图的可接受值。您还可以将逻辑包装在(显式)函数中:

  viewFor =(target) 
#有很多方法可以做到这一点...
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

给你的逻辑一个名字(即包装在一个函数中)通常有助于澄清你的代码。


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?

解决方案

There are two forms of switch in CoffeeScript:

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

and:

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

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.

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

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