UFO ET IT

커피 스크립트에서 케이스 문 전환

ufoet 2021. 1. 10. 17:50
반응형

커피 스크립트에서 케이스 문 전환


동일한 기능을 호출하는 몇 가지 다른 버튼이 있으며 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?

switchCoffeeScript 에는 두 가지 형식이 있습니다 .

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 nullif 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

논리에 이름을 지정 (즉, 함수로 래핑)하면 코드를 명확히하는 데 유용합니다.


의 세부 사항뿐만 아니라 허용 대답 , switch커피 스크립트의 문은 지원 ,여러 경기 결과를 제공하기 위해 :

switch someVar
    when val3, val4 then ...
    else ...

또는 (문에 여러 줄이있는 경우) :

switch someVar
    when val3, val4
        ...
    else
        ...

ReferenceURL : https://stackoverflow.com/questions/23046257/switch-case-statement-in-coffee-script

반응형