通过名称移除事件

获取Konva最新的信息

需要通过名称移除事件时,我们可以使用 on() 时给事件设置命名空间,之后可以使用 off() 方法设置的命名空间移除事件。

说明:点击下面的圆形可以看到两个事件绑定的 alert 弹出,点击左边的按钮移除事件监听,然后再次点击圆形观察变化。

Konva Remove By Name Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/konva@4.0.18/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Remove Event Listener by Name Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}

#buttons {
position: absolute;
top: 5px;
left: 10px;
}
</style>
</head>

<body>
<div id="container"></div>
<div id="buttons">
<button id="remove1">
Remove First Listener
</button>
<button id="remove2">
Remove Second Listener
</button>
<button id="removeAll">
Remove All Listeners
</button>
</div>
<script>
function writeMessage(message) {
text.text(message);
layer.draw();
}

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

var layer = new Konva.Layer();

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

circle.on('click.event1', function() {
alert('First Listener');
});
circle.on('click.event2', function() {
alert('Second Listener');
});

layer.add(circle);
stage.add(layer);

document.getElementById('remove1').addEventListener(
'click',
function() {
circle.off('click.event1');
alert('First onclick removed');
},
false
);

document.getElementById('remove2').addEventListener(
'click',
function() {
circle.off('click.event2');
alert('Second onclick removed');
},
false
);

document.getElementById('removeAll').addEventListener(
'click',
function() {
circle.off('click');
alert('All onclicks removed');
},
false
);
</script>
</body>
</html>