You can use Object.defineProperties on window:
function onValueUpdate(my_global_var) {
// Some arbitrary logic you want to execute on callback
console.log(`my_global_var was updated: ${my_global_var}`);
}
Object.defineProperties(window, {
_my_global_var: {
value: 'string',
writable: true
},
my_global_var: {
get: function() {
return this._my_global_var;
},
set: function(val) {
this._my_global_var = val;
onValueUpdate(this._my_global_var);
}
}
});
window.my_global_var = 'New string';
When you access window.my_global_var it behaves exactly as the property of type String would. But when you set it you can adjust it to use any additional logic.
Function onValueUpdate needs to be public (or you can use a public method instead).
There’s a warning against this approach in the answer you’ve found though:
I'd not go with getters/setters solution - it's complicated, not scalable and not maintainable.
So if you need scalability you probably should look for some library that can do that. Otherwise this should work just as well.