【问题标题】:Stimulus controller action firing twice刺激控制器动作触发两次
【发布时间】:2021-02-13 10:54:33
【问题描述】:

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

【问题讨论】:

    标签: ruby-on-rails stimulusjs


    【解决方案1】:

    原来问题出在我的application.js 文件中。我有:

    const application = Application.start()
    const context = require.context("../controllers", true, /\.js$/)
    application.load(definitionsFromContext(context))
    
    import "controllers"
    

    我不知道这行:import "controllers" 是如何到达那里的,或者我认为它做了什么,但删除它之后,事情只会触发一次。

    【讨论】:

      【解决方案2】:

      所以我知道默认情况下,表单应该侦听submit 事件,因此您不需要包含事件名称(请参阅here for event shorthands)但我想知道是否因为它是带有remote: true 的表单那么它也在监听ajax:success 事件。如果您尝试将数据操作更改为仅侦听 ajax:success 事件,是否可以解决问题?

      data: { action: "ajax:success->post#addBody" }
      

      P.S 我知道这是一种推测性的答案,因此可能需要发表评论而不是答案,但我没有发表评论的声誉点数。

      【讨论】:

      • 您好,感谢您的回复。所以我尝试了一些我认为我会在此处为某些上下文添加帖子控制器操作的事情,目前的响应是超级准系统,但从我所读到的内容来看,它构成了一个成功的响应。我尝试将ajax:success-&gt; 添加到数据操作中,也尝试在表单中添加和不添加remote: true。还没有运气,仍然射击了两次。
      猜你喜欢
      • 2023-01-01
      • 2020-11-11
      • 2022-11-18
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      • 2022-06-26
      • 2022-06-29
      • 1970-01-01
      相关资源
      最近更新 更多