1

I am using Konva js as a canvas library. I store each added element individually in a database and load them once the user enters the editor again. To achieve this I iterate over an object containing each node in json format. I am facing the problem that every function only works for the last element added (i.e. On mouse down solely the last elem_id is alerted). Any help is highly appreciated.

    function showExElem(elem_obj) {
    //Iterate over the object - create each element - assign to current layer
    for (var key in elem_obj) {
        var elem_json = elem_obj[key][0];
        var elem_container_json = elem_obj[key][1];
        var elem_id = elem_obj[key][2];
        //Transform into elem and container
        var realized_elem = Konva.Node.create(elem_json);
        var realized_elem_container = Konva.Node.create(elem_container_json);
       
        //Add to layer and redraw
        layer.add(realized_elem);
        realized_elem_container.nodes([realized_elem]);
        layer.add(realized_elem_container);

        //Draw the layer
        layer.draw();

        //On click of the element show the element container and trigger the edit fields at the top
        realized_elem.on('mousedown', function () {
            alert(elem_id);
            //Hide all other containers
            var containers = layer.find('.container');
            containers.hide();
            //Show the element container
            realized_elem_container.show();

        });

    }
}
Jakob
  • 195
  • 4
  • 12
  • 1
    `realized_elem_container` has the last value assigned to it in the `for..in` loop. Use `let` when declaring that variable. – Teemu Aug 09 '20 at 13:14
  • Looks like you can just write the answer from the @Teemu tip. – lavrton Aug 10 '20 at 22:16
  • 1
    This is a classic example of closures in the loop, there's no reason for yet another answer to the same question. – Teemu Aug 11 '20 at 06:12

0 Answers0