gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:33:21 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com