Observing objects — by Steven Lacerda (Morgan Hill, CA)
There are two ways to handle observations in javascript. We used to have Object.observe, but that is not longer available for the most part, so we have two options:
- get/set
- Proxy
First Option
var obj = {
value: "",
getValue() {
return this.value;
},
setValue(value) {
var event = new CustomEvent('data', {
detail: Object.assign(options, {
type: 'env'
})
});
document.dispatchEvent(event); return this.value = value;
}
}obj.setValue(5) // fires a custom event with a payload
obj.getValue() // 5
In this case, whenever setValue updates the value of obj, it fires a CustomEvent with a payload in detail.
The listener will look something like:
document.addEventListener('data', (evt) => {
// do something with evt.detail
});
Second Option
You can also use a proxy, which is the most recent way to handle object observation:
var obj = { value: 'test' }var proxyied = new Proxy(obj, {
get: function(target, prop) {
console.log(target, prop);
return target;
},
set: function(target, prop, value) {
var event = new CustomEvent('data', {
detail: {
type: 'env'
}
});
document.dispatchEvent(event);
console.log(target +", " + prop + ", " + value);
}
})proxyied.value = 12 // {value: "test"}, "value", 12
Where target is the object, prop is the ‘value’ prop from proxied.value and value is obviously the value we set.
In this example, dispatch event fires whenever a change is made to obj, which we can listen for in the same way we did above.
Solving a problem is as good as those sexual feelings…sometimes, okay, maybe not. Straight from Morgan Hill, CA. Good luck!