Skip to main content

HTML5 Canvas Remove Event Listener by Name with Konva

To remove an event listener by name with Konva, we can namespace the event type with the on() method so that we can later remove the event listener by the same namespace with the off() method.

Instructions: Click on the circle to see two alerts triggered from two different onclick event bindings. Remove the event listeners using the buttons to the left, and again click on the circle to observe the new onclick bindings.

Note: vue and react don't support event namespacing, so we don't make a demo for them. We don't recommend using namespacing for Vue and React anyway.

import Konva from 'konva';

const stage = new Konva.Stage({
  container: 'container',
  width: window.innerWidth,
  height: window.innerHeight,
});

const layer = new Konva.Layer();
stage.add(layer);

const circle = new Konva.Circle({
  x: stage.width() / 2,
  y: stage.height() / 2,
  radius: 70,
  fill: 'red',
  stroke: 'black',
  strokeWidth: 4,
});

// add click listeners
circle.on('click.event1', function () {
  alert('first click listener');
});

circle.on('click.event2', function () {
  alert('second click listener');
});

layer.add(circle);

// add buttons to remove listeners
const button1 = document.createElement('button');
button1.innerHTML = 'Remove first listener';
button1.style.position = 'absolute';
button1.style.top = '0';
button1.style.left = '0';
document.getElementById('container').appendChild(button1);

const button2 = document.createElement('button');
button2.innerHTML = 'Remove second listener';
button2.style.position = 'absolute';
button2.style.top = '30px';
button2.style.left = '0';
document.getElementById('container').appendChild(button2);