asim-ishaq
asim-ishaq

Reputation: 2220

Show dijit/Menu programmatically

I am working on a context menu in dijit. The code is almost done and the menu pops up as I right click the attached dom node. The problem is that I need to be able to show/hide the menu programmatically. It appears that there is no method like .show() or .hide()

here is the code:

var top_settings_menu;

require(["dojo/ready", "dijit/Menu"], function(ready, Menu) {
    ready(function() {
        top_settings_menu = new Menu();
        top_settings_menu.bindDomNode("settings");

        ...menu items
        ........

       top_settings_menu.startup();

    });
});

Here is what I need: Method to show hide the menu programmatically like: top_settings_menu.show(); top_settings_menu.hide();

Upvotes: 0

Views: 2658

Answers (1)

Paul Grime
Paul Grime

Reputation: 15104

This fiddle demonstrates two approaches, but I don't know if there's an official way to do this.

Setup the menu:

var pMenu;

require(["dojo/ready", "dijit/Menu", "dijit/MenuItem", "dijit/PopupMenuItem"], function (ready, Menu, MenuItem) {
    ready(function () {
        pMenu = new Menu({
            targetNodeIds: ["progmenu"]
        });
        pMenu.addChild(new MenuItem({
            label: "Simple menu item"
        }));
        pMenu.startup();
    });
});

function runAfterDelay(fn, ms) {
    setTimeout(function () {
        console.log("Timeout " + new Date());
        fn();
    }, ms);
}

Add the event handling.

  • Approach #1 is to call dijit/popup.close(), passing the menu as the single parameter.
  • Approach #2 synthesises a blur event to 'trick' the menu into closing.

...

require(["dojo/dom", "dojo/on", "dijit/popup"], function (dom, on, popup) {
    var timeout = 3000;
    on(dom.byId("btnPopupClose"), "click", function () {
        runAfterDelay(function () {
            if (pMenu) {
                console.log("Calling .close()");
                popup.close(pMenu);
            }
        }, timeout);
    });
    on(dom.byId("btnTriggerBlur"), "click", function () {
        runAfterDelay(function () {
            var opts = {
                bubbles: true,
                cancelable: true
            };
            console.log("emitting blur event");
            on.emit(pMenu.domNode, "blur", opts);
        }, timeout);
    });
});

Upvotes: 1

Related Questions