简体   繁体   English

jQuery、webpacker 和 Rails 6 事件监听器

[英]jQuery, webpacker & Rails 6 event listener

I have a remote:true form built using SimpleForm that renders a JS file create.js.erb我有一个使用 SimpleForm 构建的 remote:true 表单,它呈现一个 JS 文件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同时,我在 erb 视图中包含的 packs/customer/form.js 中有一个监听器,使用

<%=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.事件侦听器永远不会被触发,但是如果我将事件侦听器移动到 javascript/application.js 它可以工作。 Any idea why this might be happening?知道为什么会发生这种情况吗?

You should first use the trubolinks:load event.您应该首先使用trubolinks:load事件。 This event is called the first time the page loads and every time on a turbolink visit.这个事件在页面第一次加载和每次访问 turbolink 时被调用。

So your code in packs/customer/form.js you should look like this:所以你在packs/customer/form.js代码应该是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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