Using the Context Menu (version 1.x)

Tips & Tricks

Summary

How to add a context menu to your yFiles for HTML application.

This article was written for an older version. It is only online as a reference for customers using this old version. The information it contains is probably out of date.

The latest information can be found in the yFiles documentation

Description

The main input mode for handling the context menu interaction is ContextMenuInputMode. It is a child input mode of GraphEditorInputMode and GraphViewerInputMode by default and can be accessed with the property contextMenuInputMode.

ContextMenuInputMode is designed so that you can use any context menu implementation with yFiles for HTML. You are not bound to the implementation in demo-framework.js. However, you can use this implementation if you want to. You could also create a custom context menu implementation or use any implementation out there.

The Context Menu Demo shows the general approach to a context menu, together with the context menu implementation from demo-framework.js. This demo shows how to use a Dojo/Dijit context menu. This demo shows how to use the jQuery context menu.

The general approach works like this:

The context menu should have some kind of open and close events. That means that the context menu itself registers to the contextmenu DOM event. In the open event handler, tell ContextMenuInputMode that the menu has been opened. Alternatively, you can register to the event manually and tell the context menu to open.

In the open event of the context menu, inform ContextMenuInputMode that the menu has been opened:

var cancelEventArgs = new yfiles.system.CancelEventArgs();
graphEditorInputMode.contextMenuInputMode.menuOpening(cancelEventArgs);
if (!cancelEventArgs.cancel) {
  // input mode has been cancelled - close the menu
}

The CancelEventArgs parameter is used if ContextMenuInputMode decides that the menu shouldn't be opened, e.g. if another input mode currently has the mutex. In this case, you should close the menu.

After menuOpening has been called, ContextMenuInputMode fires the PopulateContextMenu event. In the event listener, you get the clicked item in the event args. Register to this event to populate your context menu with the desired items.

graphEditorInputMode.addPopulateItemContextMenuListener((function(sender, /**yfiles.input.PopulateItemContextMenuEventArgs.<yfiles.model.IModelItem>*/ args) {
  // populate menu with items here
}).bind(this));

In the close listener of the context menu, tell ContextMenuInputMode that the menu has been closed:

graphEditorInputMode.contextMenuInputMode.menuClosed();

Categories this article belongs to:
yFiles for HTML
Applies to:
yFiles for HTML: 1.3, 1.4
Keywords:
ContextMenuInputMode - menuOpening - addPopulateItemContextMenuListener - menuClosed