Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Giving an element more than one event handler by selecting it using different selectors

I have several "event" classes covering some of my svg elements. I'm assigning each class an event handler for mouseover and mouseout, and if an element has more than one class, I want both handlers to fire. How do I do this? It seems that when I do

d3.selectAll(".a-class")
    .on("mouseover", function() {
        // do A
    })
    .etc();

d3.selectAll(".another-class")
    .on("mouseover", function() {
        // do B
    })
    .etc();

then when I hover over an element that has both classes, only B (the second handler) fires, apparently because it overrides the first one. Is there a method to "append" an event handler, rather than redefine it?

like image 952
Bluefire Avatar asked Mar 31 '16 12:03

Bluefire


1 Answers

As per the documentation...

If an event listener was already registered for the same type on the selected element, the existing listener is removed before the new listener is added. To register multiple listeners for the same event type, the type may be followed by an optional namespace, such as "click.foo" and "click.bar".

Therefore you can achieve what you want by appending an arbitrary namespace to each of your handlers.

d3.selectAll(".a-class")
    .on("mouseover.a", function() {
        // do A
    })
    .etc();

d3.selectAll(".another-class")
    .on("mouseover.b", function() {
        // do B
    })
    .etc();

This has the added advantage that you can then refer explicitly to the added event handlers later (either individually or for an entire namespace) to replace or remove them.

like image 125
Steve Greatrex Avatar answered Oct 19 '22 18:10

Steve Greatrex