将条件和函数调用放在一行中

时间:2012-11-15 16:16:06

标签: coffeescript

有没有办法(希望是干净的)我可以在这里做同样的事情而不分配状态值? 当if条件在同一行时,我遇到if条件返回布尔值(而不是函数)的问题。

onItemChanged = (event,ui) ->
  input_element = event.target
  list_id = input_element.getAttribute('list_id')
  state = if input_element.checked
            onItemChecked //function of int -> nothing
          else
            onItemUnchecked //function of int -> nothing

  state (list_id )

2 个答案:

答案 0 :(得分:2)

像这样:

onItemChanged = (event, ui) ->
  input = event.target
  state = if input.checked then onItemChecked else onItemUnchecked
  state input.getAttribute('list_id')

甚至:

onItemChanged = ({target: input}, ui) ->
  state = if input.checked then onItemChecked else onItemUnchecked
  state input.getAttribute('list_id')

答案 1 :(得分:1)

不确定您是否认为它更干净,但您也可以直接调用if表达式的结果:

onItemChanged = (event,ui) ->
  input_element = event.target
  list_id = input_element.getAttribute('list_id')
  (if input_element.checked then onItemChecked else onItemUnchecked) list_id

或者只是拨打onItemChecked内的onItemUncheckedif

onItemChanged = (event,ui) ->
  input_element = event.target
  list_id = input_element.getAttribute('list_id')
  if input_element.checked 
    onItemChecked list_id
  else 
    onItemUnchecked list_id