Dyin
Dyin

Reputation: 5376

Delegate events to canvas and retrieve the Element in the handler

I'm using Raphaël to draw a graph (network) as nodes are represented and shown as circles. The user can dynamically add nodes by clicking on the canvas, and by that the newly constructed Element object is pushed into a Set, also into a model object, where some precious data stored about the node just created.

I want to show the mentioned data from the model near each node, when the user brings the mouse pointer over a node. What I wish to avoid is to create a new event on every node at creation. I want to delegate the event to the canvas to have a global handler for each node.

I've already created such handler and attached the event to it:

var Paper    = Raphael('Graph',600,600),
    $Canvas  = $(Paper.canvas),
    onMouseOver = function(e){
      // Wish to have an Element object
    }

$Canvas.on('mouseover','circle',onMouseOver);

The event and the handler works fine, as it fires only on circles.

How can I retrieve or take it as an Element object, and access its .data() and every associated? Do I have to search for it in my Set? If so, how?

Upvotes: 1

Views: 196

Answers (1)

bbird
bbird

Reputation: 368

Assuming the elements in your set are identified by Raphaël's Element.id then as you create new elements you can assign the equivalent id to the DOM node

newElement = Paper.circle(x, y, r);
newElement.node.id = newElement.id;

Then in your mouseover handler you can get the element's id from the event.target

onMouseOver = function(e){
  var elemId = e.target.id;
  //find your element in the set by this id to get the precious data
}

Upvotes: 1

Related Questions