Cocoon event listers are not fired in stimulus

so I am using cocoon and stimulus with latest version on rails. In the controller js file, event listener for turbolinks:before-cache gets triggered but event listeners related to cocoon are not getting triggered.
Here is the code:

document.addEventListener(“turbolinks:before-cache”, () => {
console.log(‘turbolinks:before-cache’)
}, {once: true})

document.addEventListener("cocoon:after-insert", () => {
  console.log('cocoon:after-insert')
})

document.addEventListener(“cocoon:after-remove”, () => {
console.log(‘cocoon:after-remove’)
})

I see only turbolinks:before-cache in the console log.

Hi! What’s Cocoon? :slight_smile:

Cocoon uses JQuery events, so you’ll have to use jQuery.

If you’re using webpack for Stimulus, but not for Cocoon. you’ll need to add jquery as an ‘external’ component, then require it in your controller and event listen there:

$ = require('jquery')

$('.foo').on('cocoon:after-insert', () => {...})

For webpack, in environment.js add:

environment.config.set('externals', {'jquery': 'jQuery'})

that was it! We were adding an event listener when we should have been adding on ‘on’ event. thanks!

1 Like