Created
November 1, 2023 11:26
-
-
Save skoji/a5f4e51de918f6eed92fee8081f66f62 to your computer and use it in GitHub Desktop.
observe property by proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Test extends EventTarget { | |
constructor() { | |
super(); | |
this.value = 0; | |
} | |
} | |
const test = new Test(); | |
const t = new Proxy(test, { | |
set: function(target, prop, value) { | |
target[prop] = value; | |
target.dispatchEvent(new Event(`${prop}_changed`)); | |
return true; | |
}, | |
get: function(target, prop, receiver) { | |
return Reflect.get(...arguments).bind(target); | |
} | |
}); | |
t.addEventListener('value_changed', () => { | |
console.log('value changed'); | |
}); | |
t.value = 1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment