ExtJS Drop-Down Menu w/Keyboard Shortcuts

by LeeMellinger

HTML

<link rel="stylesheet" href="http://dev.sencha.com/deploy/ext-4.0.0/resources/css/ext-all.css">

CSS

.mymenuitem-text
{
    position:absolute;
    left:3px;
    top: 6px;
}

.mymenuitem-cmdTxt
{
    position:absolute;
    right:3px;
    top: 6px;
}

JavaScript

Ext.define('MyMenuItem', {
    extend : 'Ext.menu.Item',
    renderTpl: [
        '<tpl if="plain">',
            '{text}',
        '</tpl>',
        '<tpl if="!plain">',
        '<a id="{id}-itemEl" class="' + Ext.baseCSSPrefix + 'menu-item-link mymenuitem-link" href="{href}" <tpl if="hrefTarget">target="{hrefTarget}"</tpl> hidefocus="true" unselectable="on">',
        '<img id="{id}-iconEl" src="{icon}" class="' + Ext.baseCSSPrefix + 'menu-item-icon {iconCls}" />',
        '<span id="{id}-textEl" class="' + Ext.baseCSSPrefix + 'menu-item-text mymenuitem-text">{text}</span>',
                '<span class="' + Ext.baseCSSPrefix + 'menu-item-text mymenuitem-cmdTxt" <tpl if="menu">style="margin-right: 17px;"</tpl> >{cmdTxt}</span>',
                '<tpl if="menu">',
                    '<img id="{id}-arrowEl" src="{blank}" class="' + Ext.baseCSSPrefix + 'menu-item-arrow" />',
                '</tpl>',
            '</a>',
        '</tpl>'
    ],
    onRender: function(ct, pos) {
        // Intercept the call to onRender so we can add the
        // keyboard shortcut text to the render data which
        // will be used by the template
        var me = this;
        me.renderData = me.renderData || {};
        me.renderData.cmdTxt = me.cmdTxt;
        me.callParent(arguments);
    }
});

var handleOption1 = function() {
    alert('You executed Option 1');
};

var handleOption2 = function() {
    alert('You executed Option 2');
};
    
var toolbar = Ext.create('Ext.toolbar.Toolbar', {
    items: [
        {
            xtype:'button',
            text:'File',
            menu: {
                xtype: 'menu',
                showSeparator: false,
                items: [
                    Ext.create('MyMenuItem', {
                        text: 'Option 1', 
                        cmdTxt: 'Ctrl+1',
                        handler: handleOption1
                    }),
                    Ext.create('MyMenuItem', {
                        text: 'Option 2', 
        ...