简体   繁体   中英

How do I bind an event when using Turbolinks?

I want to stop a form from posting if it's text area is blank. I'm using jQuery and Turbolinks. I have to bind on ajax:beforeSend , but I get it to work:

  $(document).on 'page:load', '.task-form', ->
    $(this).bind 'ajax:beforeSend', ->
      alert "hi"

I see no alert when submitting the form. Any idea why?

I'm loading the form remotely via ajax.

# tasks/new.js.erb
$('.task-form-wrapper').append('<%= j render("form") %>');
$('#task_name').focus();
$(document).on 'page:load', '.task-form', ->

The page:load event is not triggered on the .task-form element, it's triggered on the document . You'll have to change it to:

$(document).on 'page:change', ->
  $('.task-form').on 'ajax:beforeSend', ->
    alert 'hi'

I changed page:load to page:change otherwise it only works if the first page request is on the view with the form. page:change is triggered every time a new page is loaded.

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