Yuriy N. Yuriy N. - 1 month ago 9
Javascript Question

Prevent Knockout from loading components only once

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?

Answer

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) {
    ko.components.clearCachedDefinition(componentName);
    fn(componentName, callback);
  };
})(ko.components.get);

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