我有几个不同的按钮调用相同的函数,我希望将它们包装在 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 http://coffeescript.org/#switch在咖啡脚本中:
switch expr
when expr1 then ...
when expr2 then ...
...
else ...
and:
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
你可以省略else null
if 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
为您的逻辑命名(即将其包装在函数中)通常对于澄清您的代码很有用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)