项目中很多时候要动态创建菜单,但是ExtJs自身并没有提供这个组件。下面是我利用TreeStore实现的动态菜单的完整代码
/** * Ext Js library 4.2.1 * * 动态菜单栏 * @class Xzr.view.base.main.DynamicMenu * @extends Ext.toolbar.Toolbar * @author 王成委 * * 2014-01-23 17:20:31 * */ Ext.define('Xzr.view.base.main.DynamicMenu',{ extend:'Ext.toolbar.Toolbar', mixins: { bindable: 'Ext.util.Bindable' }, alias:'widget.dynamicmenu', displayField:'moduleName', typeField:'moduleType', applicationField:'application', controllerField:'controller', leafField:'leaf', height:36, border:false, defaults:{ style:{ marginRight:'10px;' } }, store:'sys.DynamicMenuStore', style:{ paddingLeft:'10px;', paddingRight:'10px;' }, cls:'x-fy-menubar', initComponent:function(){ var me = this; if(Ext.isString(me.store)) me.store = Ext.data.StoreManager.lookup(me.store || 'ext-empty-store'); me.bindStore(me.store); this.callParent(); }, getStoreListeners:function(){ var me = this; return { expand: me.onExpand } }, /** * 响应节点展开事件 * @private * @param {Ext.data.Model} parent * @param {Ext.data.Model[]} records * @param {Boolean} successful */ onExpand:function(parent,records,successful){ var me = this,container; if(parent.isRoot()){ me.createMenuHeader(records); return; } container = me.down('#'+parent.getId()).menu if(!container )return; Ext.Array.each(records,function(node){ me.doAdd(container,node); }); }, /** * 创建 * @param {Ext.data.Model[]} records */ createMenuHeader:function(records){ var me = this; Ext.Array.each(records,function(node,index){ var split = (index+1)<records.length; me.addParentNode(me,node,split); }); me.add('->'); me.add({xtype:'button',text:'转到',action:'scroll',iconCls: 'x-icon-list',style: 'margin-left: 8px;',style:'marginRight:5px;',menu:[]}); }, doAdd:function(container,node){ var me = this; if(node.isLeaf())me.addLeafNode(container,node); else me.addParentNode(container,node); }, //添加父节点 addParentNode:function(container,node,split){ var me = this, menuItem = { text:node.get(me.displayField), itemId:node.getId(), menu:[] }; //将菜单添加到父容器中 container.add(menuItem); if(split)container.add('-'); //展开节点 node.expand(); }, //添加子节点 addLeafNode:function(container,node){ var me = this, menuItem = { text:node.get(me.displayField), itemId:node.getId(), type:node.get(me.typeField), app:node.get(me.applicationField), controller:node.get(me.controllerField) }; container.add(menuItem); } });其原理就是向toolbar中绑定Store,并监听Store的expand事件,在expand事件中完成将节点添加到容器中的操作。
有关Store绑定的详细资料请到我的这篇博文中查看: http://blog.csdn.net/jaune161/article/details/18266301