Suppose I'd like to implement 2 way data binding without any frameworks. I know it can be achieved by several methods like Object.defineProperty()
or Proxy
. However, all of these methods require the change happens on the property of an object like obj.a = 'new value'
. Is it possible to observe the change on variables directly so I can execute my own code when name = 'new value'
is called somewhere else?
// A string variable
var name = 'some value';
function nameChanged(newValue) {
document.getElementById('name').value = newValue;
}
// magic goes here...
...
name = 'new value' // nameChanged() is automatically called.