Flex MenuBar – allowing top level elements to be selected
Out of the box the MenuBar control kind of insists that you have children for every top level menu item in order to navigate. If you don’t have any children for a MenuBarItem you don’t get an ITEM_CLICK event when it is clicked. Fixing this is pretty simple but can be a little annoying since you need to listen for MouseEvent.CLICK as well as MenuEvent.ITEM_CLICK.
Putting another listener on the menu bar is pretty simple but you need to look out for the user clicking on the menu bar but not on a menu item. My click listener looks simething like this:
public function handleMenuClick(event : MouseEvent) : void {
if(event.target is MenuBarItem) {
var menuItem : MenuItem = event.target.data as MenuItem;
if(menuItem.children == null) {
app.views.selectedIndex = menuItem.navIndex;
}
}
}
In the above example i am using a very basic custom MenuItem for the data structure of my menu. It just contains the Label, Icon and a navigation index which I apply to my ViewSstacks (in the above case the ViewStack is ‘app.views’) as the selectedIndex the class looks like this:
public class MenuItem {
public var label : String;
public var icon : String;
public var navIndex: int;
public var children : Array;
public function MenuItem(label : String, navIndex : int, icon : String) {
this.label = label;
this.icon = icon;
this.navIndex = navIndex;
}
}
If the children Array is null, I know that it is a navigation target.
July 1st, 2009 at 6:57 pm
This is good but how do I link my menuBar to a viewStack in Flex 3?
September 2nd, 2009 at 2:20 pm
Thanks for publishing. This code helped me solve my problem where you could click on the menubar and there was no item to be selected on that part of the menubar. It was throwing an error message. With the event.target is MenuBarItem, solved my problem.