Assume you have this class:
class Foo {
constructor() {
this.count = 0
}
increaseCountEventually() {
setTimeout(() => {
this.count += 1
}, Math.floor(Math.random() * 1000))
}
}
Then you create an instance of this class:
const foo = new Foo()
Then you call the increaseCountEventually
method which will, at some random point in time, increment the value of its property this.count
:
foo.increaseCountEventually()
So, in a few milliseconds count will increase by 1. Is there a trick to listen for changes in the count
property of the foo
instance? Something like an event listener, where the event would be the change of the count
property. Something like this (pseudo-code):
// A bit like DOM events
foo.addEventListener('property count changes', () => console.log('it changed!'))
// Or, in other terms:
foo.listenForCountChange(() => console.log('it changed!')
I could use setInterval
and check every millisecond or so to see if count
has changed, but I'm looking for a more efficient way. I read about using a "Proxy" but not sure how that would work.
Javascript Proxy are meant to be used on Objects. If its okay to convert count into an object or keep an object called data with property count then you could add a proxy with a set trap
In your case however, you could modify increaseCountEventually
to accept a function like so
increaseCountEventually(callback) {
setTimeout((callback) => {
this.count += 1,
callback();
}, Math.floor(Math.random() * 1000))
}