Exploring the ways to observe changes in JavaScript objects:
- Using methods, such as set/get or combined approaches
- Polling with a timer to monitor property changes
- Utilizing observers that are internally handled by the browser for property management
The first method is straightforward and commonly used. Whether to implement setter/getter functions is a personal choice. Alternatively, both can be combined:
var someValue = 0;
this.myMethod = function(newValue) {
if (arguments.length === 0) return someValue; /// returns value if no argument is provided
someValue = newValue; /// sets new value if argument is given
return this;
}
This approach is clean and easy to understand.
If opting for properties instead, one must choose between polling with a timer or utilizing an object observer.
However, support for Object observers is still limited (as of my last check). Chrome offers support, Firefox has its own observer system, etc. Therefore, code should be prepared to handle situations where support may be lacking. In such cases, using methods like set/get is a more reliable approach in my opinion.
An observer becomes useful when dealing with properties. It enables setting a property like this:
myObject.value = 10;
which triggers a callback for handling the change. Note that the callback will be triggered for any property change, so event iteration is necessary.
For instance, you could have:
Object.observe(myObject, observerCallback);
function observerCallback(records) {
records.forEach(checkRecord);
}
function checkRecord(rec) {
switch(rec.name) {
case 'value':
handleValueChange();
break;
}
}