2

Our SPA is built using .NET and uses knockoutJS for it's clientside bindings. We are binding all of our data on initial page load and are experiencing memory leaks on page reload. I am wondering the proper way to dispose of nested knockout oberservables to avoid memory leaks. I have tried

    $(window).bind('beforeunload', function () {
    ko.cleanNode(ko.vm)

});

(ko.vm being our root viewmodel) but there is still huge memory leaks. Do we need to release each subOberservable individually on page unload? Our next step is to lazy bind our data to the view..but any knockoutJS memory managing practices would be greatly appreciated.

James
  • 2,951
  • 8
  • 41
  • 55
  • I don't have the KO source in front of me but I think that cleanNode is designed to remove bindings from DOM nodes as opposed to disposing of javascript objects. We use it successfully to clean-up DOM nodes from leaking in IE7/8 but like you we're also having issues with the ViewModel not disposing properly in older IE versions. – jvhang Sep 12 '13 at 13:25

1 Answers1

2

If you are refreshing the page then the browser should be releasing any memory. If there's a memory leak, then it is a bug in the browser. What browser are you seeing this behavior? How do you know there is a memory leak?

But if you are not really refreshing the page, but are instead just removing DOM elements and replacing them with new elements and rebinding, then you do need to be careful.

Generally speaking, make sure you...

  • Dispose of any subscriptions (if you called someKoObject.subscribe(), then call dispose on the return value of subscribe to release the subscription).
  • Dispose of any ko.computed objects you make (because they are internally subscribing to things).

In many cases this all gets cleaned up for you and you do not need to do this. But in the case where the observable outlives the observer, if you do not unsubscribe, then the observer is kept in memory. If you understand the difference then you can only track and dispose of the subscriptions you know will be a problem.

If you post some of your actual code that you think is leaking and under what conditions, then more specific advice can be given.

Brandon
  • 38,310
  • 8
  • 82
  • 87
  • The reason I assume there is a memory leak is because in the chrome profiler, the memory usaage increases with each reload. Also after the serveral reloads the app consistently crashes on certain mobile devices – James Jun 07 '13 at 18:38
  • This is a [problem with old versions of IE](http://stackoverflow.com/questions/1077840/javascript-memory-leaks-after-unloading-a-web-page), but I've never heard of it in a modern browser. Can you distill it down to an example that would fit in a jsFiddle? Maybe you are doing something unusual with iframes or aren't really unloading the page. – Brandon Jun 07 '13 at 18:54