0

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?

4

1 回答 1

0

工作案例repl:https ://svelte.technology/repl?version=2.15.3&gist=7b0b820ce452cf6d5d10ebf456627651

测试.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>

应用程序.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>
于 2018-11-28T11:38:27.980 回答