hotwired / stimulus

A modest JavaScript framework for the HTML you already have
https://stimulus.hotwired.dev/
MIT License
12.67k stars 420 forks source link

Using ujs ajax events with stimulus actions #78

Closed mmlindeboom closed 6 years ago

mmlindeboom commented 6 years ago

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.

lsylvester commented 6 years ago

@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.

sstephenson commented 6 years ago

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

mmlindeboom commented 6 years ago

Thank you!

cursorzz commented 6 years ago

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

kaspermeyer commented 5 years ago

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