jQuery has nothing to do with Knockout. It can remove nodes - but this won't clean up any bound KO observables. In the given case this will mean there is a slight memory leak as KO maintains data via an internal collection (see ko.utils.domData
) after the node is simply removed with jQuery.
Two traditional methods used in KO to cleanup after itself are cleanNode
and removeNode
(however neither will remove bound events!) which should be used as needed .. using cleanNode (on a node bound via KO) is the minimum required to clean up data.
However, I don't think that this is a suitable place to manually clean up KO! The standard bindings will already handle cleanup, if used correctly.
Instead, write the code like the following. (See Creating custom bindings that control descendant bindings for withProperties
; you'll also have to make it virtual-element compatible to use it as below.)
<div id='my_div'>
<!--ko 'if': someObservable-->
<!--ko withProperties: { data: someObservable() }-->
<span data-bind="text: data.dialog_body"></span>
<!--/ko-->
<!--/ko-->
</div>
Then simply set the observable to something to create the node ..
someObservable(myVm)
.. or undefined to clear it ..
someObservable(undefined)
After all, one generally won't really $('#my_div').remove()
but will rather $('#my_div').dialog('close')
. Actually removing the node will work just as well, as long as the same element is added back later for the new dialog.
The someObservable
value could come from the "root" view model - I recommend having a root view model! - or it could come from a window property, for those feeling hackish:
window.someObservable = ko.observable()