Add a DeepObserver to recursively observe an object, all its properties, all their properties, etc.... #80
Description
Currently observe-js doesn't have any support for a DeepObserver-like object which listens for changes to an object and all its recursive subobjects. A quick search also shows I'm not the first to notice its absence:
- http://stackoverflow.com/questions/23073344/observe-changes-for-an-object-in-polymer-js
- https://esdiscuss.org/topic/deep-object-observing
- https://mindtheshift.wordpress.com/2014/07/27/object-observe-pitfalls/
Indeed, I've also seen requests for it on internal mailing lists at my company. It seems to be a common expectation that observe-js would provide one. And from a completeness standpoint, it's a bit odd that observe-js doesn't at least offer some basic solution, even if it makes sense to build your own if your requirements are different from the provided deep observer.
As it turns out, a few other observation libraries already implement their own:
As it turns out, it's not as simple a task as it might seem to build a deep observer that cleans up after itself--it's a surprisingly difficult thing to do 100% correctly. And unfortunately, I was able to find several failed attempts as projects on their own:
I think it would be worthwhile for observe-js to provide a well-tested canonical solution. To that end (and for my own projects), I pulled together a basic DeepObserver at http://jsfiddle.net/3ju5qdb2/11/. It recursively observes an object and all of its properties all the way down, allocating as few ObjectObservers as possible and making sure to clean up after itself. It doesn't handle cycles, nor are the added/remove/changed event args as useful as they could be, since they only reflect the change at the lowest level, rather than the entire path. Neither matter for our application, but they wouldn't be hard to add to make the class more generally useful.
Perhaps something like it could be added to observe-js, or as an add-on for it making it opt-in?