Hotwire Discussion

jQuery plugin event and Stimulus actions?

I’m trying to listen to a Chosen.js event (a jQuery plugin) but I’m not sure how to do this when I’m not using a build. I read these notes about listening to jQuery events on Stimulus actions:

Listening to jQuery events on Stimulus actions like ajax:success

But I’m confused as to how to incorporate jquery-events-to-dom-events - npm which the article points to.

Basically I have this element:

data-action="change->my-controller#myFunction"

And the Chosen event is

$("#form_field").chosen().change( … );

(Chosen styles a select field.)

I tried to get it working similar to the package you shared but couldn’t catch Chosen events.
A workaround could be:

import {Controller} from 'stimulus';
import 'chosen-js'

export default class extends Controller {
    connect() {
        $(this.element).chosen().change(e=>{
            console.log(e);
        })
    }
}

Not ideal though because you cannot catch the event on the controller and call a method on a different controller.