dsdsdsdsd
dsdsdsdsd

Reputation: 2962

how to remove event listener from fabricjs canvas

I am using fabricjs to build an interactive map in html5.

When the DOM loads, I add my mouseover listener to my fabricjs canvas instance by calling: *my_event_setter( true )*.

Then for the sake of testing, I want to remove the listener once I do my first mouseover by calling: *my_event_setter( false )*. That should thus remove the mouseover listener, but it does not.

my_event_setter = function( toggle )
  { var lvo =  { 'object:over' : function(e){ mouseover_handler( e ) } } ;
    toggle ? my_fabric_canvas.on( lvo ) : my_fabric_canvas.off( lvo ) ;
  } 
mouseover_handler = function( e )
  { my_event_setter( false ) ;
  } 

Upvotes: 9

Views: 15583

Answers (5)

Prawin soni
Prawin soni

Reputation: 452

function removeEvent(eventName: string) {
  let lisnr = canvas.__eventListeners[eventName][0];
  canvas.off(eventName, lisnr);
}

I'm doing this, considering there's only one event registered for "eventName". I had to do this because I had to bind few params to my listener before registering and which changes the listener instance. In the case of anonymous function, we can go with the above logic.

Upvotes: 1

Adam M.
Adam M.

Reputation: 1088

The simplest solution to destroy all the events:

canvas.__eventListeners = {}

If you want to remove only some of the events iterate through the properties of the __eventListeners object:

for (var prop in canvas.__eventListeners) {
    if (canvas.__eventListeners.hasOwnProperty(prop) && prop === 'mouse:up') {
        delete canvas.__eventListeners[prop]
    }
}

Or with new Object.keys:

Object.keys(canvas.__eventListeners).forEach((prop) => {
    if (prop === 'mouse:up' || prop === 'object:moving')) {
        delete canvas.__eventListeners[prop]
    }
})

Upvotes: 4

Kalpesh Desai
Kalpesh Desai

Reputation: 1421

Bind event with angular js like

$scope.closeCurve = function(){
    canvas.isDrawingMode = true;
    canvas.on('mouse:up', function() {
      canvas.getObjects().forEach(o => {
        o.fill = 'blue'
      });
      canvas.renderAll();
    });
  };

Remove event like

$scope.selectTool = function(){
    canvas.isDrawingMode = false;
    canvas.off('mouse:up');
  };

bind with on method and remove from off method...:)

Upvotes: 0

jdrake
jdrake

Reputation: 343

This example shows how to remove the mousemove when mouseup is fired:

canvas.on('mouse:up', function () {
    canvas.off('mouse:move', eventHandler);
});

Upvotes: 11

JesseRules
JesseRules

Reputation: 723

I solved this by using:

var canvas = fabric.Canvas.activeInstance;
canvas.__eventListeners["mouse:down"] = [];

The events are in an Array so it makes it easy to handle these.

Upvotes: 9

Related Questions