2014-04-13 11 views
45

Mam kilka różnych przycisków, które wywołują tę samą funkcję i chciałbym, aby były zawijane w instrukcji switcha, zamiast używać kilku innych, jeśli warunki. Każda pomoc będzie świetna !!!Przełącznik case case w skrypcie do kawy

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? 
+0

To nie nadaje się do instrukcji switch mimo to (hasClass vs is). – user2864740

Odpowiedz

97

w coffeescript Istnieją dwie formy switch:

switch expr 
    when expr1 then ... 
    when expr2 then ... 
    ... 
    else ... 

oraz:

switch 
    when expr1 then ... 
    when expr2 then ... 
    ... 
    else ... 

Druga forma może pomóc:

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 

Mogłeś opuścić else null, jeśli undefined jest akceptowalną wartością dla view. Można też owinąć logiki w funkcji (jawnej):

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 

Podając swoją logikę nazwę (tj owijając go w funkcji) jest często przydatne do wyjaśnienia kodu.

+8

Pamiętaj, że 'then' musi ** only ** zostanie użyte w przypisaniu do jednej linii. Nie wpisuj "wtedy", jeśli napiszesz poniższy kod, bo inaczej zawiedzie podczas kompilacji. – Vadorequest

12

Oprócz szczegółów w the accepted answer, switch oświadczenia coffeescript obsługuje również , dostarczyć wiele wyników meczów:

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

lub (jeśli sprawozdanie ma kilka linii):

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

Nie sądzę, że 'lub' jest tutaj - stworzy on 'case (val1 || val2):' statement - ie. uruchamianie operacji boolowskiej na 'val1' i' val2'- co nie jest tym, czego oczekiwałbym tutaj. '' 'Jednak działa. – Voy

+0

@Voy: masz rację - 'lub' nie daje oczekiwanego rezultatu. Odpowiedź zaktualizowana – larsmoa