Yurii N.
Yurii N.

Reputation: 5703

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?

Upvotes: 2

Views: 1513

Answers (2)

Anton Anpilogov
Anton Anpilogov

Reputation: 141

If you want to clear all registered components cache you can use this dirty hack:

Object.getOwnPropertyNames(ko.components._allRegisteredComponents).forEach(ko.components.clearCachedDefinition);

Upvotes: 1

Zoltán Tamási
Zoltán Tamási

Reputation: 12764

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.

Upvotes: 2

Related Questions