Search code examples
ruby-on-railsrubyerbstimulusjsstimulus-rails

Is there a way to make a click on a button_to bubble up to a parent element?


Here is the code I have:

<div data-controller="eta">
...
  <div data-action="click->eta#advance" data-value="2hr">
    <%= button_to '2 Hours', set_eta_order_path(@order), method: :post, params: { ... } %>
  </div>
...
(repeated several times as a list)
</div>

The button works when clicked, but the event does not bubble up to the div, so the event handler on the div is not being called.

There is a list of these divs as options to a poll, and each, when clicked should both advance to the next page and save the result you clicked. The problem is that the poll's pages are rendered almost entirely in the client (without a different route for each page), and are handled with Stimulus.js, and saving the result happens in the server.

Is there a way to make this layout compatible with itself, and if not, are there any workarounds?


Solution

  • You have to declare your data-controller:

    <div data-controller="eta">
    
      <div data-action="click->eta#advance" data-eta-time-param="1hr">
        <%= button_to "1 Hour", set_eta_order_path(@order) %>
      </div>
    
      <div data-action="click->eta#advance" data-eta-time-param="2hr">
        <%= button_to "2 Hours", set_eta_order_path(@order) %>
      </div>
    
    </div>
    
    // app/javascript/controllers/eta_controller.rb
    
    import { Controller } from "@hotwired/stimulus"
    
    // Connects to data-controller="eta"
    export default class extends Controller {
      advance(event) {
        console.log(event.params);
      }
    }