我有几个不同的按钮正在调用相同的函数,我希望将它们包装在switch语句中,而不是使用其他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
您可以忽略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
给您的逻辑起一个名字(即将其包装在一个函数中)通常对澄清代码很有用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句