Thursday, 1 June 2017

Node.js How to delete an object which has event listener and free up memory?

I am using Node.js. I have an array of objects.

var my_array = [];
var param_array = [xx, xx, ...];

for (i = 0; i < 5; i++) {
    my_array[i] = new ClassName(param[i]);

    (my_array[i]).on('event_name', function() {
        // do something
    });
}

All the objects are created from a class/library. All the objects have event listener.

After finished using the objects in the array, I want to delete all the objects and free up memory.

Based on Google search results, the Garbage Collector should automatically free up memory when the memory is not referenced by any variable anymore. So, I set the array to a new empty array:

my_array = [];

However, I was surprised to find that all the event listeners of the objects in the old array are still responding to events.

How can I delete (or dereference) all the objects which have event listener and free up memory?



via userpal

No comments:

Post a Comment