javascript - CustomEvent 监听器回调触发两次?

标签 javascript web-component custom-element custom-events

我创建了一个自定义元素:

const templ = document.createElement('template');
templ.innerHTML = `
<span><slot></slot></span>
`;
class SlideButton extends HTMLElement {

    constructor() {
        super();

        // Attach a shadow root to the element.
        const shadowRoot = this.attachShadow({ mode: 'open' });
        shadowRoot.appendChild(tmpl.content.cloneNode(true));
        this.span = shadowRoot.querySelector('span');

        this.triggerEvent = new CustomEvent("trigger", {
            bubbles: false,
            cancelable: false,
        });

        this.initMouseEvents();
    }

    initMouseEvents() {
        this.span.addEventListener('mousedown', (e) => {

            //Watch and calculate slide amount..
            this.addEventListener('mousemove', this.slide, false);

        });

        //When button is released...
        document.addEventListener('mouseup', handleMouseUp = (e) => {

            this.removeEventListener('mousemove', this.slide, false);
            document.removeEventListener('mouseup', handleMouseUp);

            //If slided enough, dispatch event...
            if (Math.abs(this.slideAmount) > (this.maxSlide * 0.75)) {
                console.log('firing event');
                this.dispatchEvent(this.triggerEvent);
            }
            //Reset button to normal state...

        }, false);
    }
}

我的代码中的其他地方..

class SpotLightModal {

    //Constructor..
    //code..
    //code..

    init() {
        this.actions.querySelector('slide-button[type="den"]').addEventListener('trigger', e => {
            console.log(e);
            console.log('den');
            //Do stuff..
        });
    }

    //code...
    //code...

}

一切都按预期工作,除了事件监听器中的回调运行两次并且输出为:

firing event
CustomEvent {...}
den
CustomEvent {...}
den

两者e.stopPropagation()e.preventDefault()没有效果,尝试使用它们没有任何效果..

我已编辑以包含 this.span并将“mouseup”事件监听器移到“mousedown”事件监听器之外,但这不起作用,事实上在记录 this 时,现在,它给出了另一个不同的元素(同一类型的 <slide-button> ,页面上的第一个元素),“mouseover”监听器不会被删除,并且事件不会被触发。

我在这里做错了什么吗?或者我到底错过了什么?

提前致谢..

最佳答案

如果其他人遇到类似问题,请尝试使用:

event.stopImmediatePropagation() 像这样进入你的回调函数

window.addEventListener('message', (event) => {
  event.stopImmediatePropagation();
  console.log('detail:', event.detail);
})

就我而言,这似乎可以解决问题,但它绝对是 super 黑客,如果需要 super 可靠,建议尝试找出问题的根本原因。

https://developer.mozilla.org/en-US/docs/Web/API/Event/stopImmediatePropagation

关于javascript - CustomEvent 监听器回调触发两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57960558/

相关文章:

javascript - 全局监控未兑现的 promise 以显示指标

javascript - polymer 元素未从字符串/文本注册到 polymer 中

javascript - 如何包含用于发布自定义 polymer 元素的外部脚本文件?

javascript - 每次使用 Vue js 时,WebComponents 都会重新初始化

javascript - 预期的 spy 不会被内部函数调用

javascript - Angular2依赖注入(inject),类继承期间不注入(inject)服务

javascript - Angular 6 自定义元素与父 DOM 交互

javascript - 我对 `data.filter` 做错了什么

javascript - 为什么 DOMParser 不使用注册的 customElements?