Vitozz_RDX
Vitozz_RDX

Reputation: 166

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 :

first fires callback A,

and second callback B

It seems that callback A stay in some kind of queue untill it called , and only then called changed callback .

So i got three questions :

1) How to remove callback A from queue before it fires

2) How to know what is in this queue

3) how much resourse consuming such operation as setting new listener on canvas (like in my case) . Maybe i should avoid it ?

Thank you !

Upvotes: 0

Views: 980

Answers (1)

shkaper
shkaper

Reputation: 4998

1) Use canvas.off(), passing 'mouse:down' and a reference to the handler. 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:

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. When an event is triggered, Fabric.js just calls the handlers in a loop. So, the cost is negligible. I'd be more concerned about the cost of the handlers themselves.

Upvotes: 2

Related Questions