1

我遇到了一个问题。我在 HAML 中使用Stimulus并使用该操作调用控制器keydown。事件侦听器被调用两次。

这是我的 HAML 代码和控制器代码:

.comments-container{ "data-controller": "comments"}
%h3.short.pull-left
    = current_tenant.label_for_field(:comment).try(:pluralize)
.button-group.action-bar
    %a.fa.fa-cloud-download.export-comments-btn{ title: "Export" }
    %a.fa.fa-archive.archive-toggle-btn{ title: "View Comments Archives" }
.comment-form
    %form
        .form-group
            %textarea.form-control{ name: "Content" , "data-target": "comments.content" }
            .tag-inputs
                %span.help-block
                    Enter a tag followed by the tab, enter, comma or semi-colon key
                %span
                    %label.tags-input-label
                        Tags:
                    %div{ "data-target": "comments.tagsContainer" }
                    %input.tags-input-input{ type: "text" , "data-action": "keydown->comments#createTag" }
            .tag-inputs
                %span
                    %label.tags-input-label
                        Users to notify:
                    %select{ type: "select" , "data-action": "comments#notifiedUsers"}
                        = options_for_select(current_tenant.users.order(email: :asc).pluck(:email, :id).unshift(["Please Select a User",nil]))
            %button.btn.btn-info{ type: "submit" , "data-action": "comments#submit"}
                = "Post #{current_tenant.label_for_field(:comment)}"
.comment-search
    %input.search{ placeholder: "Search Comments" }
.comments-items
    = render @comments

控制器.js:

    import { Controller } from "stimulus"

const getCSRFToken = () => { 
    return Array.from(document.getElementsByTagName('meta')).find(meta => meta.name === 'csrf-token').content
  }

export default class extends Controller {
    static targets = ["content", "tagsContainer", "tag"]
    connect() {

    }
    submit(e) {
        e.preventDefault()
        console.log(this.contentTarget.value)
    }
    createTag(e) {
        const keys = ["Enter", "Semicolon", "Tab", "Comma"]
        if(keys.includes(e.key)){
            e.preventDefault()
            console.log("Anything")
            this.tagsContainerTarget.insertAdjacentHTML('beforeend', `<span class="tags-input-tag"> ${e.currentTarget.value} </span>`)
        }
    }
    notifiedUsers(e) {
        e.preventDefault()
        //console.log(e.contentTarget.value)
        console.log(e.type)
    }
}
4

0 回答 0