preloader
軟體工程

Event-handling and function with JQuery in CoffeeScript | 在CoffeeScript裡使用JQuery Event-handling

Wanna use functions, which are defined in files of coffeescript language, to change one of CSS attributes such as display when an user clicking a button or element at a web page? You can follow below instructions.

At side of web page, for example:

  • Write down a button of HTML 5 for triggering event
<button type="button" name="btn-veggie-list" class="btn-veggie-list">Veggie list</button>
  • Target HTML. For example, it’s an unordered list for items in a web page
<ul class="veggie-list">
  <label><input type="checkbox" class="veggie-1" value="taro">芋</label>
  <label><input type="checkbox" class="veggie-2" value="gherkin">小黃瓜</label>
</ul>
  • <label></label> tag is used for selecting and unselecting a checkbox when we clicking text of label.

 

The other side for coffeescript file, for example:

  • Write down your function for changing display or hide mode of unordered list in .js.coffee . In this example, the function is called as display_or_not_veggie_list.
display_or_not_veggie_list = ->
  current_value = $('.veggie-list').css('display') # this is a class-selector of JQuery in Coffeescript file
  if current_value == "none"
    $('.veggie-list').css('display', 'block')
  else
    $('.veggie-list').css('display', 'none')
  • Use delegated event-handling with JQuery in a coffeescript file, which are suffixed as .js.coffee .In this example, we use it in same .js.coffee file.
$(document).on 'click', '.btn-veggie-list', display_or_not_veggie_list  # yes, it works but it will fire many events when clicking a element, e.g. button
$(document).off('click', '.btn-veggie-list').on 'click', '.btn-veggie-list', display_or_not_veggie_list # Yes, it works and better than aboved one.
$('.btn-veggie-list').on 'click', -> display_or_not_veggie_list # no, it doesn't work. So don't use this. I've modified this example from original one at stackoverflow.com in the reference. That one doesn't work for me.
  • Don’t forget to compile your .js.coffee file.

 

My environment is:

  • Rails 4.2.5.1
  • Ruby 2.3.0
  • Sass 3.4.21
  • Sass-rails gem 5.0.4
  • CoffeeScript 1.10.0
  • Coffeescript gem 2.4.1
  • Coffee-rails gem 4.1.1
  • Coffee-script-source 1.10.0
  • JQuery-rails gem 4.1.0
  • Turbolinks gem 2.5.3 # I don’t turn off it in my rails project.

 

Reference:

  1. https://www.iexposure.com/industry-insights/rails-4-turbolinks-and-delegated-event-handling-in-jquery
  2. http://stackoverflow.com/questions/24923366/use-a-coffeescript-create-function-inside-a-onclick-attribute?sgp=2
  3. JQuery click events firing multiple times http://stackoverflow.com/questions/14969960/jquery-click-events-firing-multiple-times/20881348#20881348