Visualizing dependencies for computed fields in Knockout
dependencies, knockout.js
Solution
I have written a plugin for Knockout (2.0+) whose primary purpose is eliminating duplicate updates for computed observables. But since the plugin replaces the `ko.computed` object, I have also added the ability to get a list of the dependencies/dependents for observables. Each computed object has a `getDependencies` method that returns an array of observables, and each observable/computed observable has a `getDependents` method that returns an array of computed observables.
Problem
Is there a way in knockout.js to determine - which values (`ko.observable` or `ko.computed`) depend on each other in what way (precedents/dependents) and - which HTML nodes (text binding, for starters) depend on the current value1, so I can highlight them on screen. ? 1 This implies that I need a way to go from an HTML node to the connected `ko.subscribable`, not just to the view model, like `ko.dataFor()` does. This seems to be impossible as well. I've built a web application that works like a spreadsheet - many numeric values that are based on each other according to a set of business rules. Some of them are calculated, some of them user-provided. At the moment I'm using my own JS library that does all the dependency tracking and dynamic screen-updating. This works, but I'd like to swap it with knockout.js for added versatility and elegance. Knockout keeps track of this information somewhere. How can I use it? For example, imagine a spreadsheet (an HTML table) that sums up a few integers: ``` | A B C --+--------- 1 | 4 1 5 2 | 2 3 | 3 8 ``` - When the user clicks on cell B3, I'd like to find out that it depends on B1 and B2 and that C3 depends on it. - When the user clicks on cell C3, I'd like to find out that it depends on A1, B1, C1, B2 and B3.