简体   繁体   中英

Coffeescript function within function not being called on click

I'm sure this is simple but I can not make this function be called on the click event. I have tried various incarnations but can't get it to play nicely. If I move the if/else loop within each click event it works without problem. I'd just like to make the code a little DRY by moving the loop to a single reference function. Is this a syntax issue or a logic problem? - Thanks in advance.

DOES NOT WORK

$(".filter_option").click ->
      $('#submission_list').children(".item ").show()
      checkIfItemsEmpty()

$('#current_filters').on 'click', 'a.filter_remove', ->
      $('#submission_list').children(".item").hide()
      checkIfItemsEmpty()

checkIfItemsEmpty = () ->   
  if !$('.item').filter(':visible').length
      $('#no_results').show()
      console.log('The show command was triggered')
  else
      $('#no_results').hide()
      console.log('The hide command was triggered')

WORKS

$(".filter_option").click ->
      $('#submission_list').children(".item ").show()
      if !$('.item').filter(':visible').length
         $('#no_results').show()
         console.log('The show command was triggered')
      else
         $('#no_results').hide()
         console.log('The hide command was triggered')

$('#current_filters').on 'click', 'a.filter_remove', ->
      $('#submission_list').children(".item").hide()
      if !$('.item').filter(':visible').length
         $('#no_results').show()
         console.log('The show command was triggered')
      else
         $('#no_results').hide()
         console.log('The hide command was triggered')

This was a simple case of formatting it turns out, which I realised two seconds after I posted!

Seems the

checkIfItemsEmpty = () ->   
  if !$('.item').filter(':visible').length
      $('#no_results').show()
      console.log('The show command was triggered')
  else
      $('#no_results').hide()
      console.log('The hide command was triggered')

Has to be outdented past the jQuery -> to work.

So....

jQuery ->
   $(".filter_option").click ->
      $('#submission_list').children(".item ").show()
      checkIfItemsEmpty()

   $('#current_filters').on 'click', 'a.filter_remove', ->
      $('#submission_list').children(".item").hide()
      checkIfItemsEmpty()

checkIfItemsEmpty = () ->   
  if !$('.item').filter(':visible').length
      $('#no_results').show()
      console.log('The show command was triggered')
  else
      $('#no_results').hide()
      console.log('The hide command was triggered')

Works like a dream now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM