简体   繁体   中英

jQuery, webpacker & Rails 6 event listener

I have a remote:true form built using SimpleForm that renders a JS file create.js.erb

// customers/create.js.erb
...
  $('#new_customer').trigger('customer:callback');
...

Meanwhile I have a listener in packs/customer/form.js that is included in the erb view using

<%=javascript_pack_tag 'customers/form'%>

// packs/customers/form.js
$(document).on('customer:callback', '#new_customer', function(data) {
  alert('Success');
});

The event listener is never triggered, however if I move the event listener to javascript/application.js it works. Any idea why this might be happening?

You should first use the trubolinks:load event. This event is called the first time the page loads and every time on a turbolink visit.

So your code in packs/customer/form.js you should look like this:

$(document).on("turbolinks:load", function () {
  $("#new_customer").on("customer:callback", function(data){
    alert("Success");
  });
});

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