刺激控制器动作触发两次

问题描述

我是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"这行是怎么到达的,或者我认为它是怎么做的,但是删除它之后,事情只会触发一次。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...