Ответ 1
В CoffeeScript есть две формы switch
:
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
, если 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
Предоставление вашей логики имени (т.е. обертывание его в функции) часто полезно для уточнения кода.