mousedown.konva事件侦听器在设置shape.dragable(false)后取消挂起



当我忘记了这个怪癖时,这是一个自我回答的问题,部分是为了我未来的自己,希望它能省去其他人为自己寻找解决方案的麻烦

所以我正在编码一个客户形状。我想听听mouse&触摸形状上的事件,所以我使用了带有.kova后缀的事件,例如mousedown.konva。这些事件是由konva自己设置的,所以我只需要添加自己的侦听器。这也适用于Rect和Circle等标准形状。

然而,我观察到一个"错误",在设置myShape.draggable(false(后,mousedown.konva侦听器停止被启动。

看起来像这个

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

rect2 = new Konva.Rect({
x: 400,
y: 100,
width: 100,
height: 100,
stroke: 'magenta',  
fill: 'magenta',  
draggable: true
}),   

rect3 = rect2.clone({x: 510, fill: 'cyan', stroke: 'cyan'});

layer.add(rect2, rect3);
stage.add(layer);


rect2.on('mousedown.konva', function(evt){
console.log('rect2.mousedown');
})
rect2.on('mousemove.konva', function(evt){
console.log('rect2.mousemove');
})
rect2.on('mouseup.konva', function(evt){
console.log('rect2.mouseup');
})
rect2.on('click.konva', function(evt){
console.log('rect2.click');
})
rect2.on('dragstart.konva', function(evt){
console.log('rect2.dragstart');
})
rect3.on('click', function(){
stage.draggable(false);
layer.draggable(false)  
rect2.draggable(false);
})
body {
margin: 10;
padding: 10;
overflow: hidden;
background-color: #f0f0f0;
} 

<script src="https://unpkg.com/konva@8/konva.min.js"></script>
<p>Mouseover, click & drag the pink rect and watch the console. Pay attention to mousedown messages. Now click the blue rect (sets pinkrect.draggable(false). Now try mousedown on the pink rect again - tis gone!!</p>


<div id="container" class='container'>

什么东西?

因此,如果您查看konva/nod.ts的代码,您将看到以下内容,当您更改形状上的可拖动属性时会触发该内容。

_dragChange() {
if (this.attrs.draggable) {
this._listenDrag();
} else {
// remove event listeners
this._dragCleanup();
/*
* force drag and drop to end
* if this node is currently in
* drag and drop mode
*/
var stage = this.getStage();
if (!stage) {
return;
}
const dragElement = DD._dragElements.get(this._id);
const isDragging = dragElement && dragElement.dragStatus === 'dragging';
const isReady = dragElement && dragElement.dragStatus === 'ready';
if (isDragging) {
this.stopDrag();
} else if (isReady) {
DD._dragElements.delete(this._id);
}
}
}
_dragCleanup() {
this.off('mousedown.konva');
this.off('touchstart.konva');
}

使用的关键点是第6行中的函数this_调用dragCleanup((。在该函数中,您可以在代码末尾看到,mousedown.konva侦听器被删除。请注意,开发人员已重试"off",因此它只影响konva侦听器。美好的

结论-不要依赖lib作者提供的事件-除非声明为保证,否则不信任他们是务实的。

最新更新