I recently had the need to lazy load a list of items using Knockout JS. Luckily, this problem has already been solved…mostly. I suggest you go read that post for the concept behind how lazy loading with Knockout works in general.
The part that was missing from that implementation for me was the Knockout array methods that are usually on an observableArray. E.g., when you do this using the code from the aforementioned post:
You will get an error saying push is undefined on your lazy observable. The problem lies in the fact that ko.lazyObservable is returning a computed observable that wraps another observable with some lazy loading behavior. The computed observable that is returned has none of the knockout methods for manipulating arrays. Even if we simply update the inner value to be an observableArray rather than a plain observable within the lazyObservable, we are still never exposing that object. It is safely tucked away as a private variable in our lazyObservable.
To make a long story short, I ended up adding another lazy method, lazyObservableArray which exposes all of the underlying knockout methods for manipulating arrays.
That technique for delegating calls to an underlying object I stole directly from the knockout source code since that is how it does some of its magic with observableArray methods.
Using this new method, we can now run our previous code with a lazyObservableArray and happily push, pop, remove or do whatever we want to our array without fear of undefined functions.