获取 DOM 元素上的所有事件:
// Get my div
myDiv = dojo.byId("myDiv");
// Obtain all event-related attributes
var events = dojo.filter(
myDiv.attributes,
function(item) {
return item.name.substr(0, 2) == 'on';
}
);
// Execute first found event, just for fun
eval(events[0].value);
如果您使用 dojo.query 获取 myDiv,请记住 dojo.query 返回一个数组,因此您的元素将位于 myDiv[0] 中。
此解决方案不适用于 dojo.connect 附加的事件。可能有一种方法可以从 Dojo 内部工作中提取此信息,但您必须深入研究源代码才能了解具体方法。
另一种选择是使用全局注册表显式管理所有 dojo.connect 事件。您可以使用 dojox.collections 来简化此操作。例如,创建一个全局注册表,其键将是 dom 节点,值将是 dojo.connect 返回的句柄(这些句柄包含 dom 节点、事件类型和要执行的函数):
// On startup
dojo.require(dojox.collections.Dictionary);
eventRegistry = new dojox.collections.Dictionary();
...
// Registering an event for dom node with id=myDiv
var handle1 = dojo.connect(dojo.byId("myDiv"), "onclick", null, "clickHandler");
// Check if event container (e.g. an array) for this dom node is already created
var domNode = handle1[0];
if (!eventRegistry.containsKey(domNode))
eventRegistry.add(domNode, new Array());
eventRegistry.item(domNode).push(handle1);
...
// Add another event later to myDiv, assume container (array) is already created
var handle2 = dojo.connect(dojo.byId("myDiv"), "onmouseover", null, "mouseHandler");
eventRegistry.item(domNode).push(handle2);
...
// Later get all events attached to myDiv, and print event names
allEvents = eventRegistry.item(domNode);
dojo.forEach(
allEvents,
function(item) {
console.log(item[1]);
// Item is the handler returned by dojo.connect, item[1] is the name of the event!
}
);
您可以隐藏烦人的检查,通过创建 dojox.collections.Dictionary 的子类并已合并此检查来查看事件容器是否已创建。创建一个js文件,路径为fakenmc/EventRegistry.js,并将其放在dojo、dojox等旁边:
dojo.provide('fakenmc.EventRegistry');
dojo.require('dojox.collections.Dictionary');
dojo.declare('fakenmc.EventRegistry', dojox.collections.Dictionary, {
addEventToNode : function(djConnHandle) {
domNode = djConnHandle[0];
if (!this.containsKey(domNode))
this.add(domNode, new Array());
this.item(domNode).push(djConnHandle);
}
});
使用上面的类,您必须使用 dojo.require('fakenmc.EventRegistry') 而不是 'dojox.collections.Dictionary',并且只需直接添加 dojo 连接句柄而无需其他检查:
dojo.provide('fakenmc.EventRegistry');
eventRegistry = new fakenmc.EventRegistry();
var handle = dojo.connect(dojo.byId("myDiv"), "onclick", null, "clickHandler");
eventRegistry.addEventToNode(handle);
...
// Get all events attached to node
var allEvents = eventRegistry.item(dojo.byId("myDiv"));
...
这段代码没有经过测试,但我想你已经明白了。