Cocoon callbacks aren't firing on Rails6

198 Views Asked by At

My problem is similar to the one described in https://github.com/nathanvda/cocoon/issues/399.

Adding and removing nested fields works, but callbacks don't fire.

application.js:

import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"

// Bootstrap
require("bootstrap")

// Toastr
global.toastr = require("toastr")

// Cocoon
require("@nathanvda/cocoon")

import "../stylesheets/application"
require("packs/ingredient")

Rails.start()
Turbolinks.start()
ActiveStorage.start()

ingerdient.js

$(document).on('ready page:load turbolinks:load', function() {
    $("a.add_fields")
      .on('cocoon:before-insert', function () {
          console.log('before insert');
      })
      .on('cocoon:after-insert', function () {
          console.log('after insert');
      })
      .on("cocoon:before-remove", function () {
          console.log('before remove');
      })
      .on("cocoon:after-remove", function () {
          console.log('after remove');
      });

   $("a.add_fields").on('click', function(){
     console.log('looks like clicking works...');
   });
});

Console output:

Event Listeners:

jquery.js:4487:

Maybe the problem is double jQuery but I'm newbie and I can't figure it how solve that.

Thanks.

1

There are 1 best solutions below

0
nathanvda On

The OP registered the callbacks on the link, but it is recommended to register them on the container object.

Quoting from the cocoon documentation:

Note that for the callbacks to work there has to be a surrounding container to which you can bind the callbacks.