PDA

View Full Version : Menu observer


schmidetzki
02-23-2007, 01:19 PM
The problem:
You have several menus in your application (f. e. a main menu plus a context menu) and need to enable or disable menu items depending on the sate of your application.
If you have a menu item "edit" in the main menu AND the context menu, you habe to disable both.

I implemented this using a observer attribut in all menu items and implemented a central observer modul handling all menu states:

BI={}; // name space
BI.menu={};
BI.menu.main = new Ext.menu.Menu({
{ text: "edit ...",
observer: "edit-page",
}
});
BI.menu.context = new Ext.menu.Menu({
{ text: "edit ...",
observer: "edit-page",
}
})
And implemented a function, to enable/disable ALL menu items with the same observer in one step:

BI.enablemenus=function(observer, enable){
for(m in BI.menu){
var items=BI.menu[m].items;
items.each(function(item){
if(item.observer && item.observer==observer)
enable ? item.enable() : item.disable()
})
}
}

When i finde a situation in my application where edit is not allowed I simply call
BI.enablemenus("edit-page", false)
... and all edit-menu-items in all menus will be disabled.

simeon
02-23-2007, 02:25 PM
In your example, what is "BI" represent?

Simeon

schmidetzki
02-23-2007, 02:38 PM
In your example, what is "BI" represent?
Sorry. I forgett BI={}. Added it to the code sample.
Its just a namespace (stands for "Browser Interface").

lumar
02-23-2007, 06:10 PM
Keep in mind that if you have nested menu's your functiion in the each method will have to take that into account.

Another approach (AOP style :) ) is to leverage the MenuMgr's register method and add functionality that will allow you to dynamically manipulate any menuitem before the Menu is shows. For example:



var beforeMenuShows = function(m){
// here we can iterate over the menuitems
// and do whatever you need to do with the menuitems dynamically
};

var newRegister = Ext.menu.MenuMgr.register.createSequence(function(menu){
menu.on("beforeshow", beforeMenuShows);
});

Ext.menu.MenuMgr.unregister.createInterceptor(function(menu){
menu.un("beforeshow", beforeMenuShows);

});
Ext.menu.MenuMgr.register = newRegister;


There are plenty of otherways to do this I just happend to like the createInterceptor and createSequence methods a lot :D