User Tools

Site Tools


js:dojo_tree_context_menu

Context Dijit.Menu with Dijit.Tree

May 2016

Searching for an implementation of a context menu with a dijit.tree, I found out the best example here. Although it was working fine, I needed a more updated version of this code (to be consistent with Dojo version 1.11 at this time). So this is my approach (original code vs new one):

Original code - partial

    var menu = new dijit.Menu();
    menu.bindDomNode(treeControl.domNode);
    menu.addChild(new dijit.MenuItem({
        label: "Simple menu item"
    }));
 
    dojo.connect(menu, "_openMyself", this, function(e) {
        var tn = dijit.getEnclosingWidget(e.target);            
        // prepare the menu
        dojo.forEach(menu.getChildren(), function(child){
            menu.removeChild(child);
 
            menu.addChild(new dijit.MenuItem({
                label: "dynamic " + store.getLabel(tn.item)
            }));
        }, this);
 
    });

Improved version - relevant part

var menu = new dijit.Menu({
    targetNodeIds: [treeControl.id]
  });
 
  menu.addChild(new dijit.MenuItem({
      label: "Simple menu item"
  }));
 
  dojo.aspect.after(menu, "_openMyself", function(deferred, args) {
    var tn = dijit.getEnclosingWidget(deferred.target);
 
    dojo._base.array.forEach(menu.getChildren(), function(child) {
      menu.removeChild(child);
 
      menu.addChild(new dijit.MenuItem({
        label: "dynamic " + tn.item.label + " - " + tn.item.id
      }));
    });
 
    return true;
  }, true);

Keep in mind now that you need to include “dojo/on”, “dojo/aspect” and also “dojo/_base/array” as convenience.

JSFiddle demo here.

js/dojo_tree_context_menu.txt · Last modified: 2016/05/26 10:27 by admin