PDA

View Full Version : Simple Menu Builder



zizac
29 Aug 2007, 7:43 AM
I ran into a situation where I have to repeat creating menus from dataStore, so I created this little helper class. Hope its useful to others too :D



MenuBuilder = {
buildMenu: function(config) {
var menu = new Ext.menu.Menu();
var dataStore = config.dataStore;
dataStore.addListener('load',function() {
this.loadMenu(config,menu);
},this);

if(config.load) {
dataStore.load();
}else {
this.loadMenu(config,menu);
}

return menu;
},
loadMenu: function(config,menu) {
menu.removeAll();
nameField = config.nameField;
handler = config.handler;
config.dataStore.each(function(item){
menu.addItem(new Ext.menu.Item({
text: item.get(nameField),
handler:function() {
handler(item);
}
}));
});
}
}

three options for config:
dataStore: the data Store
nameField: the name of the store field to be put as menu item
handler: call on each item function pass the item clicked on

use it


newTicketMenu = MenuBuilder.buildMenu({
dataStore:this.myDataStore,
handler: function(item) {
someFunction({name:item.get('name'),id:item.get('id')});
},
nameField:'name',
load:true
});

possible extension:

a config option called functionField(item)
to create a custom MenuItem's text base on the item of the dataStore