问题描述
我是StimulusJS的新手,我只想显示在用户添加新帖子时在其他帖子之后附加的帖子内容。一切似乎正常,但是帖子被附加了两次,因此看起来该表单已提交了两次。
<div data-controller="posts">
<div data-target="posts.add">
</div>
<!-- this is from a rails partial but it's all inside the data-controller -->
<%= form_with scope: :post,url: posts_path,method: 'post',data: { action: "post#addBody" } do |form| %>
<%= form.text_field :content,class: "form-control",data: { target: "posts.body"} %>
<%= form.submit class: "btn btn-primary" %>
</div>
实际控制器:
import { Controller } from "stimulus"
export default class extends Controller {
static targets = ["body","add"]
addBody() {
let content = this.bodyTarget.value;
this.addTarget.insertAdjacentHTML('beforebegin',`<div>${content}</div>`);
}
}
我知道这是可行的,因为当表单提交时,它会在页面上显示帖子,但是再次调用该函数,并且该帖子出现两次。我已经用debugger
进行了尝试,似乎Stimulus内部的某些东西第二次调用了addBody()
?
在上下文中,这是posts_controller的工作:
def create
@post = current_user.post.build(post_params)
respond_to do |format|
if @post.save
format.json {head :ok}
else
raise ActiveRecord::Rollback
end
end
end
解决方法
因此,我知道默认情况下,表单应侦听submit
事件,因此您无需包括事件名称(请参见here for event shorthands),但我想知道是否是因为它是表单与remote: true
一起使用时,它也在监听ajax:success
事件。如果您尝试将数据操作更改为仅侦听ajax:success
事件,那么是否可以解决该问题?
data: { action: "ajax:success->post#addBody" }
P.S我知道这是一种推测性的答案,因此可能需要评论而不是答案,但是我没有声誉点可以发表评论。
,原来问题出在我的application.js
文件中。我有:
const application = Application.start()
const context = require.context("../controllers",true,/\.js$/)
application.load(definitionsFromContext(context))
import "controllers"
我不知道import "controllers"
这行是怎么到达的,或者我认为它是怎么做的,但是删除它之后,事情只会触发一次。