Fork me on GitHub

Shape events

Shapes feature events. However those events are fired at the Graph level, to avoid registering too many event handlers which would slow down jsGraph and use up too much memory.

NB: In the future, shape-specific event emitting will likely be introduced as well. Stay tuned for updates

The events that shape fire are the following

  • shapeNew - Fired when a shape is created
  • shapeRemoved - Fired when a shape is removed
  • shapeChanged - Fired whenever a shape has changed (color, style, position, size, …). This event depends partly on the inherited shape implementation code and may therefore not be fired properly.
  • shapeBeforeMove - Fired before a shape is set for moving. Use graph.prevent() to prevent the subsequent shape moving.
  • shapeMoved - Fired after a shape has moved
  • shapeBeforeResize - Fired before a shape is set for resizing. Use graph.prevent() to prevent the subsequent shape moving.
  • shapeResized - Fired after a shape has been resized
  • shapeSelected - Fired when a shape is selected
  • shapeUnselected - Fired when a shape is unselected
  • beforeShapeMouseMove - Fired when the shape has focus and before any mouse move event is implemented (resize, move or anything else, really). Use graph.prevent() to prevent the shape from performing any further action at this stage
  • shapeMouseOver - Fired when the mouse enters the shape perimeter. The perimeter depends on the shape type and whether you are using a bounding box.
  • shapeMouseOut - Fired when the mouse leaves the shape perimeter.

Attaching event listeners

Like mentionned above, attaching event listeners is done at the {@see Graph} level. The first argument in the event callback is the shape instance that you can use to compare with a known reference:

var rectangle = graph.newShape("rect", { selectable: true, position: [ { x: "100px", y: "100px" }, { dx: "100px", dy: "100px" } ] } ).draw();
rectangle.getPosition( 1 ).relativeTo( rectangle.getPosition( 0 ) ); // Just fix the positioning of pos2 vs pos1
graph.on("shapeSelected", function( shape ) {
	
  if( shape == rectangle ) {
    // Do something for this specific rectangle
  }

  if( shape.getType() == "rect" ) {
    // Do something for all rectangles
  }
});

Select the rectangle to trigger the ```shapeSelected``` event