Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout cleanNode() removes jquery event bindings?

Knockout's cleanNode() function seems to be removing jQuery's event bindings on elements inside the node. How can I prevent this?
There is not much documentation I could find on cleanNode() either.

like image 389
Atharva Johri Avatar asked May 10 '13 09:05

Atharva Johri


2 Answers

Directly from the knockout docs:

"Overriding the clean-up of external data

When removing an element, Knockout runs logic to clean up any data associated with the element. As part of this logic, Knockout calls jQuery’s cleanData method if jQuery is loaded in your page. In advanced scenarios, you may want to prevent or customize how this data is removed in your application. Knockout exposes a function, ko.utils.domNodeDisposal.cleanExternalData(node), that can be overridden to support custom logic. For example, to prevent cleanData from being called, an empty function could be used to replace the standard cleanExternalData implementation:"

ko.utils.domNodeDisposal.cleanExternalData = function () {
    // Do nothing. Now any jQuery data associated with elements will
    // not be cleaned up when the elements are removed from the DOM.
};

Lately i went crazy because of endless debug sessions.

I saw this question, and I hope my answer gives a more immediate solution for those who are still searching.

like image 197
T-moty Avatar answered Nov 15 '22 17:11

T-moty


@T-moty answer is working fine, so i wrote a short function that override the cleanExternalData method, call clearNode and set original method back.

    private koClearNode(element: HTMLElement)
    {
        var original = ko.utils.domNodeDisposal['cleanExternalData'];
        ko.utils.domNodeDisposal['cleanExternalData'] = function () { };
        ko.cleanNode(element);
        ko.utils.domNodeDisposal['cleanExternalData'] = original;
    }

Also works in TypeScript, where cleanExternalData is not in typings.

like image 34
prespic Avatar answered Nov 15 '22 17:11

prespic