Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage knockout view-model collection in javascript

Tags:

knockout.js

I am using knockoutJS as a client-side MVVM framework.

Sometimes I am creating a temporary view models (via js functions) and assign them to DOM elements that are dynamically loaded.

When, for example, a comments panel for some content is no longer needed, I remove the comments panel div from the DOM. What happens to the variable that was used as a view model when I called applyBindings with specifying a DOM element parameter? It is being somehow disposed? Or am I responsible to handle that? If so - how do I do this?

like image 920
Maxim V. Pavlov Avatar asked Nov 03 '22 15:11

Maxim V. Pavlov


1 Answers

Assign your viewModel to a variable:

var viewModel = {...}
ko.applyBindings(viewModel, $("#html-id"));

To destroy the viewModel:

ko.cleanNode($("#html-id"));
delete viewModel;
$("#html-id").remove();

I haven't tried this yet, but it's what I'm planning to use in a new project that will have dynamically loaded/destroyed modules...

like image 96
Mike B Avatar answered Jan 04 '23 13:01

Mike B