I want variables from addEventListener functions to be taken into account when calculating the final, global variable. I know that by default they remain in local / block / function scope. Can this be somehow worked around? I am trying to calculate price (global variable) based on local variables from click events (input, drop-down list and 2 checkboxes). When I declare it I get a message that local variables are not defined. It’s understandable because event hasn’t happened yet. Even after it does I can read updated values of local variables in browser console but global variable still remains undefined.
Asked
Active
Viewed 69 times
-1
-
It is very hard to debug code we cannot see. Please post a [MCVE] – CertainPerformance Feb 22 '20 at 11:46
-
[Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Andreas Feb 22 '20 at 11:48
1 Answers
0
At the top of your file, declare the global var you want to mutate:
var EvilGlobalPriceVariable = 0
Then in the handlers, mutate that. Do that for every variable you want to affect in the handlers. Best to make it an object if you have more than one:
var EvilGlobalState = {
mutateMeHandlers: 0,
mutateMeToo: 0
}

Josh Wulf
- 4,727
- 2
- 20
- 34