For some reason, my stimulus controller, load once, but the action is fired twice on click.
I can't find where the issue is...
我的代码很简单,所以我在下面分享一下:
// app/javascript/application.js
https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"
// app/javascript/controllers/application.js
import { Application } from "@hotwired/stimulus"
const application = Application.start()
application.debug = false
window.Stimulus = application
export { application }
// app/javascript/controllers/index.js
import { application } from "controllers/application"
import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"
eagerLoadControllersFrom("controllers", application)
// app/javascript/controllers/radio_button_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static classes = [ 'active', 'inactive', 'invisible' ]
connect() {
console.log('connected to ', this.element.querySelector('input').value)
}
markAsChecked(event) {
event.stopPropagation();
console.log('-', this.element.querySelector('input').value);
}
}
// view.html.erb
<div class="flex flex-1 gap-x-8 justify-start">
<label data-controller="radio-button" data-action="click->radio-button#markAsChecked:stop">
<input type="radio" value="public" name="destination[access_type]" id="destination_access_type_public">
</label>
<label data-controller="radio-button" data-action="click->radio-button#markAsChecked:stop">
<input type="radio" value="private" name="destination[access_type]" id="destination_access_type_private">
</label>
<label data-controller="radio-button" data-action="click->radio-button#markAsChecked:stop">
<input type="radio" value="backend" name="destination[access_type]" id="destination_access_type_backend">
</label>
</div>
当我在开发人员控制台中运行以下命令时,我也得到了双重动作触发
// developer console
temp1 // label
temp1.click()
// - public
// - public
temp2 // input
temp2.click()
// - public
As you can see, markAsChecked is triggered twice when I click on the label, and once when I click on the input. I have no idea why...
(I expect it to always trigger once)