如何修复使用Stimulus和HAML两次调用的事件控制器

时间:2019-12-06 23:59:46

标签: haml stimulusjs

我遇到了一个问题。我在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

controller.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)
    }
}

0 个答案:

没有答案