Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS Memory Leak

I'm fairly certain I'm having memory leaks using KO version 2.0. I have an observable array that is populated with the result of an AJAX call. This collection is data-bound with a for each to a DIV container. Each object in the array has one single observable value that is bound to a checkbox. I've examined the heap using Chrome and my conclusion is the following:

If the AJAX call returns 3 elements, they are rendered properly on the DOM. If I take a snapshot of the heap at this point, there are three SearchResult objects in there. If I trigger the AJAX call again and it returns 5 elements, all 5 are correctly rendered to the DOM. However, if I take a snapshot of the heap in Chrome, and compare them, there are 8 elements listed as still being on the heap, all of them listed as being "added" and none are listed as "deleted". The DOM display is always correct, but the memory use just keeps climbing and climbing because the old search results are never deallocated.

Can anyone help me or give me pointers for diagnosing the memory leak?

UPDATE

I've created a jsFiddle to show the gist of what I'm doing. I've striped down EVERYTHING but the core functionality and I can still duplicate the memory leak when running on my local machine. Obviously the code won't work as it's posted because it needs to hit my local server to run the search.

UPDATE 2

I pulled the newest 2.1.0.0 Beta version and the leak disappeared. I'm not a huge fan of using beta version of things or of the classic "just upgrade to the new version" fix. I am still very interested in knowing what changed or what I was doing wrong that was creating the leak.

like image 660
arb Avatar asked Mar 24 '12 17:03

arb


People also ask

What is KnockoutJS used for?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.

How do you activate a KnockoutJS model?

To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.

What is Knockout data?

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.

Is Knockout open source?

Knockout was developed and is maintained as an open source project by Steve Sanderson.


1 Answers

You're not doing anything wrong, it looks like ko.cleanNode was ignoring foreach bindings and not properly disposing of the outdated objects within the updated observableArray.

https://github.com/SteveSanderson/knockout/issues/271

This has been fixed in 2.1.0beta

like image 98
KodeKreachor Avatar answered Oct 26 '22 14:10

KodeKreachor