I’ve been using Knockout.js quite extensively but there’s one pattern I use a lot where I’d like to understand how it actually works.
Often I’ll have an ObservableArray of some view model, such as productModule.products(). Then I’ll have various filter functions such as productModule.getAvailableProducts() which uses an array filter (I currently use Underscore.js) to return a subset, and that function is what gets bound to the UI. What I don’t quite understand is how, given that these functions return a standard array rather than an ObservableArray, that Knockout’s bindings still update when I change the underlying ObservableArray. Here’s an example fiddle:
Does Knockout determine at binding time whether a particular binding resolves to an ObservableArray even if via other functions? If so, can there be an arbitrary number of such functions in the chain?
Any help in understanding this is much appreciated.
Bindings are actually executed within a computed observable that is used to track dependencies. So, if you call a function that accesses observables, then they will contribute to the dependencies of that element’s bindings. When the dependency changes, then the binding s will run again.
This post goes into a little bit more detail: http://www.knockmeout.net/2012/06/knockoutjs-performance-gotcha-3-all-bindings.html