artuska artuska - 28 days ago 17
AngularJS Question

Angular DOM event namespace

How do I namespace my DOM events in AngularJS?

I have some directives that bind mouse events on the Document:

$document.on('mousemove');
$document.on('mouseup');


After mouseup I do:

$document.off('mousemove');
$document.off('mouseup');


And then some other directives does not work, because events were destroyed.

In Angular's documentation for angular.element is written:

on() — Does not support namespaces, selectors or eventData


Well, but I think I need event namespaces to target which events to remove. So, what should I do?

Answer

Even though jqLite doesn't support namespaces (yet, at least), you can always use .off() with a handler param, to specify which listener you should remove. For example:

function mouseMoveHandler() {
  // do some stuff
}
$document.on('mousemove', mouseMoveHandler);
// ... and later on
$document.off('mousemove', mouseMoveHandler);