1

I am trying to use paperjs to create shapes. I also want to implement undo functionality, so when the shape is created I push it into a undoList

        const myCircle =  new Path.Ellipse({
            point: firstPoint,
            size: calculateSize(firstPoint, secondPoint)
        });
        this.undoList.push({
            name: myCircle.name,
            id: myCircle.id,
            type: "shape",
            object: myCircle
        });

Then I change the color of this created circle and again push to undoList.

        myCircle.strokeColor = "#ffffff;

        this.undoList.push({
            name: myCircle.name,
            id: myCircle.id,
            type: "shape",
            object: myCircle
        });

In my undo function, I am trying to delete the item using item.remove(). This item is fetched using the id of undoList. After removing, I add the previous element of undoList if it has the same id (so that previous state is restored).

Now although I have changed the color, both the items in the undoList have the same color. So, there is no change visible. I think this is happening because they are both pointing to the same object.

How can I overcome this issue?

helloworld
  • 1,002
  • 3
  • 15
  • 27

1 Answers1

4

You are manipulating 2 references that simply point to the same object.

What you can do is the following:

  • Every time you make a change to your Item, do an Item.exportJSON() and store the JSON in your undo list. This way you store the data of the Item as a String, instead of a reference.
  • When you want to undo/redo just .pop() off your stack and do myCircle.importJSON(json).

This is just one way to do it, but it's not really efficient in terms of memory consumption.


Side note: You might want to look into using the Command Pattern instead; The basic idea is that you store actions you take on your Item's instead of snapshotting their whole data every time you undo/redo.

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167