CANVAS how to add or remove instances using click event


I need to create a Python object to add or remove instances. The idea is to have a picture where the user clicks on and adds or removes an “X” mark.

Right click on an automatically generated instance and copy it:
Paste that into the script editor and assign it to a variable . Add whatever params you need in there and append it to the instances prop.

If you add multiple instances using this, you will have to mess with the top/left parameters to prevent unwanted overlap. Consider using the Flex Repeater if you need positioning to be automated.

1 Like

Great idea, thanks for the feedback, I will try both and check what fits better in my program.

In both situations (canvas or flex repeater), how can I delete the instance if the user clicks on the “x”.
For example, if I have 10 instances and the user clicks at the instance 4 to remove.

Make the view that contains your X mark clickable. Give the view an id, that will appear in the instances prop of the canvas.
In the onClick event, add a script. In that script, send a message, with the id of the view as payload.
In your canvas, add a message handler that listens to the message sent by the X mark view.
Upon reception of this message, delete the instance that corresponds to the id received in the payload.

edit: forget what I just wrote, the canvas component has a onInstanceClicked event.
Use that instead of sending messages

1 Like

What would be the script to delete the instance?

well I though using del self.props.instances[event.index] or self.props.instances.pop(event.index) would work, but it seems quite buggy - sometimes it does delete the instance, sometimes it doesn’t and create another one instead (because clicking the canvas creates a new mark).

I’m not sure how to fix that, I’ll try a couple things but I don’t have much time.

Thanks a lot, it was really helpful.
I will try it.

well it actually seems to work:

I had to put the add X mark action to the double click event, as clicking on an instance also triggered the addition of a mark. Couldn’t find a prevent default for the onInstanceClicked event, which I guess kinds of messes things up.
With double click for addition though, the removing part works fine.

1 Like