variable change | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 1

variable change

how to notice the change in js

12th Sep 2020, 5:07 PM
Aparty
Aparty - avatar
1 Antwort
+ 1
I'm not sure if you want JavaScript to listen and react to changes in this variable or you want a way to manually review changes to the variable. I'll answer both cases. If you just want to see the value of a variable at a given time to troubleshoot a problem, I would use console.log(x); console.error(x); or add a breakpoint in the source of your browser's developer tools. From a stopped breakpoint, you can type the variable in the JavaScript console to see its value. If you want to listen to changes in a variable like you might listen to changes of value in an input, there are a few approaches. All approaches require at least a few minor changes to the type of variable you work with. KnockoutJS has something called an observable. It is a type of value you can subscribe/listen to. An observable is an object wrapped around the number, string, or whatever simpler type you want to observe. Say you had var x = 4; and you wanted to observe when x changed. You'd change that to something like var x = ko.observable(4); Then you could add a function that listens for changes like: x.subscribe(function() { console.log('x changed to ' + x()); }); Instead of x = 5; to change the value, you'd do something like: x(5); More details at: https://knockoutjs.com/documentation/observables.html If this "variable" happens to be "property", you're in luck. For example, you have an object.x, you can convert that from a simple number to something with get and set functions that are called when the value is being assigned a new value or being read from. This means you could call any other function you want from set and know when it is changing, check call stack to see what is changing it... You could add a breakpoint in set if you're troubleshooting something. https://www.w3schools.com/js/js_object_accessors.asp
12th Sep 2020, 9:25 PM
Josh Greig
Josh Greig - avatar