An important fact that most of us are missing is that Knockout holds some internal data structure to manage its magic. Basically, every time you call ko.applyBindings a new management record is added to KO internal representation.
Consider the following scenario,
- An HTML template was downloaded from the server and is held inside the browser memory (as a normal string)
- You use jQuery to clone the template and create an HTML element out of it
- You destroy the HTML element when it is not needed any more
I hope you agree that this kind of manipulation is quite common for single page application
The problem, as I mentioned before is that destroying the HTML element is not enough. As result of using KO applyBindings mechanism KO is holding some global data which indirectly contains a reference to your view model.
To see this issue in action, open the attached sample and perform the following
- Take a heap snapshot using Chrome developer tools
- Click Create, Bind and then Destroy (do not click Unbind)
- Take another snapshot
- Ask Chrome to perform comparison of the two snapshots
You will then noticed that an object of type ViewModel was created but was not collected by the garbage collector
Now, run the same scenario but this time click Create, Bind, Unbind and then Destroy
As you can see, this time a ViewModel object was created and destroyed by the garbage collector.
So, what did the “Unbind” button do? Short answer: ko.cleanNode
To summarize, you should consider using ko.cleanNode before destroying an HTML element. Else, you end up with memory leaks !