Search code examples
javascriptdatamaps

new Datamap() keeps a shared state of memory between invocations


It seems that with this code:

var map = null;
map = new Datamap({
    // Conf 1 ...
});
// Draw map on DOM
// Remove map from DOM and recreate another map
map = null;
map = new Datamap({
    // Conf 2 ...
});

after the second assignment map and the resulting Datamap is a mixture of Conf 1 and Conf 2. How this could happen?

Here is a live demo: https://jsfiddle.net/mztyLh66/7/


Solution

  • The problem was due to Datamap implementation of defaults.

    In the line of code:

    if (obj[prop] == null) obj[prop] = source[prop];
    

    obj[prop] is a pointer to source[prop], this cause a shared state of memory between different instances of new Datamap().

    I've addressed the problem using a deep copy:

    // Deep copy if property not set
    if (obj[prop] == null) {
        if (typeof source[prop] == 'function') {
            obj[prop] = source[prop].bind({});
        }
        else {
            obj[prop] = JSON.parse(JSON.stringify(source[prop]));
        }
    }
    

    and opened a pull request to fix it.