Skip to the content.

knockout/pager - possible solution for DOM teardown

Possible solution to DOM leakage issue with PagerJS as I observed previously (Knockout is great, not sure about pager):

Add an afterHide event handler to tear down DOM after you leave for another page.  This handler can wipe the DOM from the template, triggering any cleanup registered with ko.utils.domNodeDisposal (see this post on StackOverflow).

Also, by clearing the reference to the view model within the Page object, the view model may be garbage-collected.   This should work for both lazy and non-lazy bindings: for lazy bindings, only the Page object would have a reference to the view model.  For non-lazy, someone else passed a reference to an existing view model so the view model will hang around.

You could attach this callback globally or within individual page bindings.

var afterHideCallback = function afterHideCallback(event) {
var elementToDestroy = event.page.element;

// clear out reference from the node with page binding so it can be garbage collected
event.page.ctx = {};

// shut down and wipe DOM from page to be hidden
$(elementToDestroy).children().each(function destroyChildElement() {
ko.removeNode(this);
});
};

// attach this event globally or in individual "page: {afterHide: ...}" bindings
pager.afterHide.add(afterHideCallback);
Written on January 16, 2014