Search code examples
javascripthtmlhtml5-canvasmootoolskonvajs

Can't access children of Konva Stage after cloning


I have a problem with konvajs. I have a konva Stage that I clone into a temporary Stage, so I can revert changes made by a user, when the user cancels. The way I do this is, that I clone the existing Stage into a temporary one, destroy the children of the origin and after that I move the children of the temporary Stage back to the original and destroy the temporary Stage. The problem is, when I try to access the children now, for example via findOne('#id-of-child'), I get undefined, even though the children exist.

Here's what I've done so far:

clone: function()
{
  var cloned_stage = this.stage.clone();

  Array.each(this.stage.getChildren(), function(layer, lidx) {
    if (layer.attrs.id) {
      // setting the id to the ones, the children had before
      cloned_stage.children[lidx].attrs.id = layer.attrs.id;
    }
  });
  return cloned_stage;
},

restore: function(tmp_stage)
{
  this.stage.destroyChildren();

  Array.each(tmp_stage.getChildren(), function(layer, lidx) {
    var tmp_layer = layer.clone();
    tmp_layer.attrs.id = layer.attrs.id;
    tmp_layer.moveTo(this.stage);
  }.bind(this));
  tmp_stage.destroy();
  this.stage.draw();
},

Now when the user opens the toolbox to change something, the current stage is cloned with the "clone" function and when the user cancels his changes, the "restore" function is called with the cloned stage as parameter. But after that when I try to do things like the following they do not work as expected.

some_child_of_the_stage.getLayer();      ->     returns null 
var edit_layer = this.stage.findOne('#edit-layer');     ->    returns undefined

But the "some_child_of_the_stage" does exist and has a layer of course and the stage has a child with the id "edit-layer".

Me and my colleague are at our wit's end.

I appreciate any help and suggestions thank you.

Update: A short fiddle showing the problem via console.log: fiddle


Solution

    1. It is better not to touch attrs property of a node and use public getters and setters.

    2. Konva has special logic for storing id property. Selector by id #edit-layer may not work because of direct access to attrs id.

    3. You can use name property fo that case.

    https://jsfiddle.net/s36hepvg/12/