由于要做一个树状菜单结构,就简单参考了一下 extjs menu 的源代码。
Class Ext.menu.Menu
Package: | Ext.menu |
Defined In: | Menu.js |
Class: | Menu |
Subclasses: | ColorMenu , DateMenu |
Extends: | Observable |
A menu object. This is the container to which you add all other menu items. Menu can also serve as a base class when you want a specialized menu based off of another component (like
Ext.menu.DateMenu for example).
发现一个处理挺巧妙的,比如我们点击一个菜单弹出子菜单,然后离开到页面空白处,点击一下所有菜单都会自动关闭。
当如,处理不难,全局监控 click 好了,可要写的优雅如 extjs 那就太难为了。Extjs 中的这方面处理主要由 Ext.menu.MenuMgr 负责 ,当new 一个新的 menu 时,在他的构造函数中:
Ext.menu.MenuMgr.register(this);
将自己注册到了一个全局,由
MenuMgr 来管理自己的外部交互。
而
MenuMgr 则监控 menu 的显示事件
menu.on("show", onShow); function onShow(m) { var last = active.last(); lastShow = new Date(); active.add(m); if (!attached) { Ext.getDoc().on("mousedown", onMouseDown); attached = true; } if (m.parentMenu) { m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3); m.parentMenu.activeChild = m; } else if (last && last.isVisible()) { m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3); } }
可见,在 menu 显示时,同时在 document 监控
mousedown 事件
function onMouseDown(e) { if (lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")) { hideAll(); } }
于是在页面其他部位点一下,所有的 menu 都隐藏了,O(∩_∩)O~