coffeescript - Switch case statement in coffee script -


i have few different buttons calling same function , have them wrapped in switch statement instead of using bunch of else if conditions. great!!!

events: "click .red, .blue, #black, #yellow" : "openoverlay"  openoverlay: (e) ->   e.preventdefault()   e.stoppropagation()  target = $(e.currenttarget)  # view should opened view =    if target.hasclass 'red' new app.redview   else if target.hasclass 'blue' new app.blueview   else if target.is '#black' new app.blackview   else     null  # open view app.router.overlays.add view: view if view? 

there 2 forms of switch in coffeescript:

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

and:

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

the second form might you:

view = switch   when target.hasclass 'red' new app.redview   when target.hasclass 'blue' new app.blueview   when target.is '#black' new app.blackview   else null 

you leave out else null if undefined acceptable value view. wrap logic in (explicit) function:

viewfor = (target) ->     # there lots of ways 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 

giving logic name (i.e. wrapping in function) useful clarifying code.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -