Stimulus: Using ujs ajax events with stimulus actions

Created on 31 Jan 2018  路  5Comments  路  Source: hotwired/stimulus

First of all, thank you for Stimulus -- it's great.

I'm wondering if it is possible currently or planned to be able to bind to ujs ajax events with stimulus's action binding syntax.

I have a modal I want to close on an ajax:success event after the modal's form is submitted . Placing the data attribute data: {action: 'ajax:success->modal#close'} on the form doesn't seem to bind, or I haven't been able to suss out my error.

It's no problem to bind it manually once the controller is connected, but the action syntax is pretty nifty.

Most helpful comment

As @lsylvester says, you鈥檒l need to make sure to use rails-ujs, which emits regular DOM events instead of jQuery events.

All 5 comments

@mmlindeboom Are you using jquery_ujs or rails-ujs UJS adapter? I don't have any problems listening to ajax:* events when using rails-ujs but I get nothing when using jquery_ujs, I think cause they are jquery events instead of dom events.

As @lsylvester says, you鈥檒l need to make sure to use rails-ujs, which emits regular DOM events instead of jQuery events.

Thank you!

how could I use rails-ujs in webpacker? [edited]

I find the solution for myself. but leave a reference for someone has same question like mine

If you're using the Webpacker gem or some other JavaScript bundler, add the following to your main JS file:

import Rails from 'rails-ujs';
Rails.start()

reference: https://github.com/rails/rails/tree/master/actionview/app/assets/javascripts#es2015

PS: rails 5 has ujs build-in

If you are working on a project where you can't switch from jquery_ujs to rails-ujs, I've proposed a solution here:
https://gist.github.com/kaspermeyer/7fe28bb7c55c2810e7b5f3d5e67c1a44

I did a small write-up about it on the Stimulus Discourse:
https://discourse.stimulusjs.org/t/listening-to-jquery-events-on-stimulus-actions/573

Was this page helpful?
0 / 5 - 0 ratings

Related issues

saneef picture saneef  路  4Comments

thiagomajesk picture thiagomajesk  路  4Comments

chocnut picture chocnut  路  4Comments

ngan picture ngan  路  3Comments

jaredcwhite picture jaredcwhite  路  3Comments