0

I recently stumbled across events in Javascript and thought it would be a pretty good method passing Data on certain situations. Now I got the problem, that I dont know how to pass Variables through CustomEvent details correctly. I'd really appreciate if you'd take a look and maybe help me :)

var testVar = 5;
const myEvent = new CustomEvent('testEvent', {
    detail: {
        myVar: testVar
    }
} )
addEventListener('testEvent', (e) =>{
    console.log("testVar:" + e.detail.myVar)
})
dispatchEvent(myEvent)
testVar = 2
dispatchEvent(myEvent)

When I use the function dispatchEvent(myEvent) i thought I'd always get the current Number stored in testVar.

Expected Output:

"testVar : 5"

"testVar : 2"

Actual Output:

"testVar : 5"

"testVar : 5"

Pixel2203
  • 1
  • 1
  • this happens with all objects, not just custom events, as you can see here: https://jsfiddle.net/zuv3cnyf/ – GrafiCode Sep 10 '22 at 09:53
  • Welcome to Stack Overflow! Please visit [help], take [tour] to see what and [ask]. Do some research, ***[search for related topics on SO](https://www.google.com/search?q=Pass+Variable+in+Javascript+CustomEvent+site:stackoverflow.com)***; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan Sep 10 '22 at 09:57
  • You assigned the VALUE of testVar to detail.myVar. It will never change by simply changing the variable that was used to assign the value in the first place. It's the same logic as for even non-object variables i.e.: x = 5; y = x; x = 2; y // returns 5 – Foxcode Sep 10 '22 at 10:06

0 Answers0