Przemek
Przemek

Reputation: 175

Svelte event dispach (component) and one-liners

I actually don't seek a solution, as I already know it. I'm just trying to understand what did actually happen before. So any elaborate explaining is highly appreciated.

Disclaimer: I already know that I probably had this wrong from the beginning, but I was not aware, because it well.. worked.

I used to do like this:

<!-- Component.svelte -->
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
</script>

<button on:click={dispatch('myEvent')}> Click me </button>

And, it was working properly. Suddenly, I needed to go back to old project and change something, that made me update package.json. And it stopped working. Error message is:

Failed to execute 'addEventListener' on 'EventTarget': parameter 2 is not of type 'Object'.

Now I just need to use proper syntax

<button on:click={() => dispatch('myEvent')}>

So, my question is - why it was working at all and (probably) which package update was crucial for that to happen. I was using that syntax quite consistently, so I'd like to avoid that in future (at least not when I'm in a hurry). My package.json from the moment it worked:

{
  "name": "app-name",
  "version": "0.7.0",
  "scripts": {
    "build": "rollup -c",
    "autobuild": "rollup -c -w",
    "dev": "run-p autobuild start:dev",
    "start": "node index.js",
    "start:dev": "nodemon index.js"
  },
  "devDependencies": {
    "@rollup/plugin-commonjs": "^21.0.1",
    "@rollup/plugin-json": "^4.1.0",
    "@rollup/plugin-node-resolve": "^13.1.3",
    "eslint": "^8.7.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^4.0.0",
    "nodemon": "^2.0.15",
    "npm-run-all": "^4.1.5",
    "prettier": "^2.5.1",
    "rollup": "^2.65.0",
    "rollup-plugin-css-only": "^3.1.0",
    "rollup-plugin-livereload": "^2.0.0",
    "rollup-plugin-svelte": "^7.1.0",
    "rollup-plugin-terser": "^7.0.2",
    "svelte": "^3.46.2"
  },
  "dependencies": {
    "axios": "^0.26.1",
    "dotenv": "^14.2.0",
    "express": "^4.17.2",
    "googleapis": "^92.0.0",
    "lodash": "^4.17.21",
    "sirv-cli": "^2.0.0",
    "socket.io": "^4.4.1",
    "socket.io-client": "^4.4.1",
    "sweetalert2": "^11.3.6"
  }
} 

Thanks a lot to help me understand!

Upvotes: 0

Views: 204

Answers (1)

brunnerh
brunnerh

Reputation: 184534

This never "worked", the only difference is probably that older versions of Svelte did not throw an error.

No error: Svelte v.3.47.0
Error: Svelte v.3.48.0

The difference is that the dispatcher function returns a boolean in the newer version whereas it returned nothing in the older one. Calling addEventListener with a handler of undefined does nothing but true/false causes the error.

Associated pull request: https://github.com/sveltejs/svelte/pull/7064

Upvotes: 1

Related Questions