我是 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