【发布时间】:2019-09-16 15:59:08
【问题描述】:
我创建了一个自定义元素:
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>,页面上的第一个),“鼠标悬停”侦听器不会被移除,事件也不会被触发。
我在这里做错了吗?或者我到底错过了什么?
提前谢谢..
【问题讨论】:
-
我认为这是因为您将事件嵌套在事件中。
-
@ChrisHemmens 我尝试以不同的方式订购它们,但没有任何效果.. 其他订单导致事件多次触发或根本不触发
标签: javascript web-component custom-element custom-events