I am trying to listen to a Select2 event in a Stimulus controller via the data-action
.
I have a stimulus controller, where I have included an event listener for Select2 events, but I cannot listen for the Select2 event from the HTML.
import { Controller } from 'stimulus';
export default class extends Controller {
initialize() {
const $element = window.$(this.element);
$element.select2({
});
$element.on('select2:select select2:unselect', (_event) => {
this.element.dispatchEvent(new Event('change'));
});
}
}
I have to listen to the "change" event with the Stimulus data-action
attribute, instead of "select2" events. The following code works. Listening via data-action-"select2:select"
does not work.
<%= f.select :name, ['name1', 'name2'], data: {'controller' => 'select2'} %>
I would like to listen to events with the data-action
attribute, as Stimulus is intended to be used.
Can I listen for Select2 events with Stimulus?
jQuery.trigger('select2:select');
, usingjQuery.Event()
. For an example on how to force jQuery to dispatch events to the DOM so Stimulus can listen for them see: jQuery Event delegation. Then you could usedata-action="jquery:select2:select->controller#method"
– Bunting