I've created a custom element:
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);
}
}
Somewhere else in my code..
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...
}
Everything works as expected except that the callback in the event listener is runs twice and the output is:
firing event
CustomEvent {...}
den
CustomEvent {...}
den
Both e.stopPropagation()
and e.preventDefault()
have no effect and trying to use them did nothing..
I've edited to include this.span
and also moved the "mouseup" event listener outside the "mousedown" event listener but that didn't work, infact when logging this
, now, it gives another different element (of the same kind, <slide-button>
, the first on the page), the "mouseover" listener doesn't get removed, and the event isn't fired.
Am I doing something wrong in here? or what am I missing exactly?
Thanks in advance..