我有几个不同的按钮调用相同的函数,我希望将它们包装在 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
如果 undefined
是 view
可接受的值,则可以省略 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/