简体   繁体   English

如何从设置事件侦听器中删除过时的回调?

[英]How to remove obsolete callback from set event listener?

I got canvas with set callback on mouse click : 我在画布上单击鼠标设置了回调:

var canvas = new fabric.Canvas('canvas');
canvas.on('mouse:down', function (options) {
    console.log('it is a starting callback')
});

Also i got button that changes callback on another one : 我也有更改另一个回调的按钮:

var btn = document.getElementById('btn');
btn.addEventListener('click', () => {
    canvas.on('mouse:down', function (options) {
        console.log('second callback')
    })
});

I thought that after firing button event first callback () will never be called , but i mistake : 我以为触发按钮事件后,永远不会调用第一个callback(),但是我错了:

first fires callback A, 首先触发回调A,

and second callback B 和第二个回调B

It seems that callback A stay in some kind of queue untill it called , and only then called changed callback . 似乎回调A停留在某种队列中,直到它调用为止,然后才称为更改回调。

So i got three questions : 所以我有三个问题:

1) How to remove callback A from queue before it fires 1)如何在触发前从队列中删除回调A

2) How to know what is in this queue 2)如何知道此队列中的内容

3) how much resourse consuming such operation as setting new listener on canvas (like in my case) . 3)在画布上设置新的侦听器之类的操作消耗了多少资源(例如在我的情况下)。 Maybe i should avoid it ? 也许我应该避免它?

Thank you ! 谢谢 !

1) Use canvas.off() , passing 'mouse:down' and a reference to the handler. 1)使用canvas.off() ,传递'mouse:down'和对处理程序的引用。 Since you're using an anonymous function as a handler, you'll need to refactor to use a named function, or just remove all listeners altogether: 由于您使用匿名函数作为处理程序,因此需要重构以使用命名函数,或完全删除所有侦听器:

const handler1 = function () {
  console.log('handler1')
}
// attach event listener
canvas.on('mouse:down', handler1)
// remove event listener
canvas.off('mouse:down', handler1)
// OR remove all 'mouse:down' listeners
canvas.off('mouse:down')

2) In Fabric.js, event handlers are stored as an array in __eventListeners property of an Observable object: 2)在Fabric.js中,事件处理程序作为数组存储在Observable对象的__eventListeners属性中:

const handler1 = function () {
  console.log('handler1')
}
canvas.on('mouse:down', handler1)
console.log(canvas.__eventListeners)
// or, more specifically
console.log(canvas.__eventListeners['mouse:down'])

3) Setting a new event listener is just pushing a new handler into the said array. 3)设置新的事件侦听器只是将新的处理程序推入所述数组。 When an event is triggered, Fabric.js just calls the handlers in a loop. 触发事件时,Fabric.js只会在循环中调用处理程序。 So, the cost is negligible. 因此,成本可以忽略不计。 I'd be more concerned about the cost of the handlers themselves. 我会更担心处理程序本身的成本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM