Reputation: 9523
I have this code in my component that is essentially the same as the example in the svelte docs:
export default {
methods: {
assessmentMouseover(e) {
const event = new CustomEvent('assessment-mouseover', {
detail: 'something',
bubbles: true,
cancelable: true,
composed: true, // makes the event jump shadow DOM boundary
})
this.dispatchEvent(event)
},
},
// -- snip --
}
I then have this code in the script tag of the HTML page that instantiates this component which is also essentially the same as the svelte docs:
const el = document.querySelector('#radar');
el.addEventListener('assessment-mouseover', event => {
console.log('got here')
});
However, when I trigger the event, I get this error: this.dispatchEvent is not a function
.
I've tried a number of variations on this.dispatchEvent()
like simply
dispatchEvent()
, which doesn't error but also doesn't trigger the listener;
and window.dispatchEvent()
which also fails to trigger.
What am I doing wrong?
Upvotes: 2
Views: 5876
Reputation: 676
Working case repl: https://svelte.technology/repl?version=2.15.3&gist=7b0b820ce452cf6d5d10ebf456627651
Test.html:
<button id="{id}" on:mouseover="doMouseOver(event)">
{isOver}
</button>
<script>
export default {
data() {
return {
isOver: 'Over Me!'
}
},
methods: {
doMouseOver(e) {
const event = new CustomEvent('assessment-mouseover', {
detail: Math.random(),
bubbles: true,
cancelable: true,
composed: true, // makes the event jump shadow DOM boundary
})
//this.dispatchEvent(event)
let source = e.target || e.srcElement
source.dispatchEvent(event)
}
}
}
</script>
App.html:
<h1>From Test: {text}</h1>
<Test id="radar"/>
<script>
export default {
components: {
Test: './Test.html'
},
data() {
return {
text: 'Wait for over'
}
},
oncreate() {
const el = document.querySelector('#radar')
el.addEventListener('assessment-mouseover', event => {
this.set({text: event.detail})
})
},
}
</script>
Upvotes: 1