Search code examples
javascriptknockout.jsknockout-componentsknockout-3.2

Why is component being disposed in params change?


According to ko's component documentation on a component lifecycle:

If the component binding’s name value changes observably, or if an enclosing control-flow binding causes the container element to be removed, then any dispose function on the viewmodel is called just before the container element is removed from the DOM

I am not sure why my component is being disposed on this fiddle.

<div data-bind='component: { name: "some-component", params: foo }'>
    <p data-bind="text: name"></p> 
</div>
function ComponentViewModel(params) {
}

ComponentViewModel.prototype.dispose = function() {
    console.log('disposing...');
};

ko.components.register('some-component', {
    viewModel: ComponentViewModel, 
    template : '<div></div>'
});

var rootvm = {
    foo : ko.observable('1')
};

ko.applyBindings(rootvm);

setTimeout(function() {
    rootvm.foo('2'); // this is disposing ComponentViewModel, why ??
}, 3000);

I can't see any of above's points in the documentation occurring on my fiddle. I certainly don't expect a component to be disposed and re-instantiated if the params injected change.

Any ideas why this is happening?


Solution

  • You are passing component parameters in the wrong way: KnockoutJs requires an object with keys and values, you are passing in an observable. I didn't dig into the details of why that ends up triggering disposal, but if you pass an object as it expects, the dispose function is not invoked anymore.

    <div data-bind='component: { name: "some-component", params: {foo: foo} }'>
        <p data-bind="text: name"></p> 
    </div>