Yuriy N. Yuriy N. - 7 months ago 64
Javascript Question

Prevent Knockout from caching loaded components

The documentation says:

Multiple component loaders may be consulted, until the first one
recognises the component name and supplies a viewmodel/template. This
process only takes place once per component type, since Knockout
caches the resulting definitions in memory.

The problem is that I don't want to load the template for component only once, I need to do it every time I add my component in a list. How can I prevent Knockout from loading components only once?


You can use the ko.components.clearCachedDefinition function, which accepts a component name. This function clears the cached component definition.

As a first option, you can call this cache clearing inside your component viewmodel constructor for example, so that you apply this logic only for that component.

As a second option, if you need this logic globally, you can try to replace the original ko.components.get function like this. Note, that this is kind of a hack, and you should test it also with the minified build, as the behavior might differ.

ko.components.get = (function(fn) {
  return function(componentName, callback) {
    fn(componentName, callback);

Also note, that I didn't test this snippet in any ways, use this technique at your own risk.