I have a hierarchy of nested KnockoutJS Components using 3.2.0. It\'s working very well but I\'m looking to execute some code once my entire hierarchy of components has been loa
Here is what worked for me. I did not try it in all possible variations such as mixing sync and async components, or using custom component loaders.
There is a method in KO 3.3.0 that all components loading goes through:
ko.components = { get: function(componentName, callback) { ...
the get
method is invoked with a desired componentName
and when component has been loaded - a callback
is invoked.
So all you need to do is wrap ko.components.get
and callback
and increment pendingComponentsCount
on each call, and decrement it after callback
is executed. When count reaches zero it means that all components were loaded.
25 lines of JS code (using underscorejs).
You also need to handle a special case where ko.applyBindings
did not encounter any components, in which it also means that all components (all zero of them) were loaded.
Again, not sure if this works in every situation, but it seems to be working in my case. I can think of few scenarios where this can easily break (for example if somebody would cache a reference to ko.components.get
before you get to wrap it).