nathanvda / cocoon

Dynamic nested forms using jQuery made easy; works with formtastic, simple_form or default forms
http://github.com/nathanvda/cocoon
MIT License
3.08k stars 383 forks source link

preventDefault issue #632

Open hksk opened 2 months ago

hksk commented 2 months ago

Im using adminsitrate with nestedHasmany gem, and I got some errores for cocoon + turbo

currently I report a issue here: https://github.com/nickcharlton/administrate-field-nested_has_many/issues/81

when a Turbo page is loaded , the event is added to "Add" button , so If I navigate 10 times with turbo, when i click the add button, then 10 childs forms are created

I do a bad patch to fix that

replacing the add field event to remove the listener

  document.querySelectorAll('.add_fields').forEach(function(element) {
    // Correctly remove the event listener
    element.removeEventListener('click', addFieldListener);
    // Add the event listener again
    element.addEventListener('click', addFieldListener);
  });

  function addFieldListener(e) { ...

and works.. someone knows if this is a normal issue?

nathanvda commented 2 months ago

Which version of cocoon/rails/turbo are you using? In the current cocoon code (which is already pretty old) there is no addFieldListener but we dynamically catch click-events on the link.

Try installing the latest version of cocoon (1.2.15).

hksk commented 2 months ago

I add a addFieldListener to make it works, with the original code, not working gem

to make it better I paste the diff:

40c40,47
<   $(document).on('click', '.add_fields', function(e) {
---
>   document.querySelectorAll('.add_fields').forEach(function(element) {
>     // Correctly remove the event listener
>     element.removeEventListener('click', addFieldListener);
>     // Add the event listener again
>     element.addEventListener('click', addFieldListener);
>   });
> 
>   function addFieldListener(e) {
103c110
<   });
---
>   };
134c141,142
<   var hideRemoveFields = function() {
---
> 
>   $(document).on("ready page:load turbolinks:load", function() {
141c149
<   };
---
>   });
143,147d150
<   $(function() {
<     hideRemoveFields();
<     $(document).on('page:load turbolinks:load turbo:load', hideRemoveFields); // Turbolinks support
<   });
<   
150a154
> 

after the change, the duplications stops and works fine.

nathanvda commented 2 months ago

Where are you including your javascript in the page? It seems with each navigation/load the javascript is evaluated again, with turbo this should normally not be the case.

hksk commented 2 months ago

Im using administrate gem, they include in the top part of the layout:

https://github.com/thoughtbot/administrate/blob/main/app/views/layouts/administrate/application.html.erb#L27

but after verify my installed gem of administrate I see it in the bottom part

I will update to the master branch of the gem or the beta and back.