如何使用dojo接收附加到元素的所有事件?
dojo.query('#mydiv') // which events does #mydiv has?
Run Code Online (Sandbox Code Playgroud)
要获取 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);
Run Code Online (Sandbox Code Playgroud)
如果您使用 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!
}
);
Run Code Online (Sandbox Code Playgroud)
您可以通过创建 dojox.collections.Dictionary 的子类来隐藏烦人的检查以查看是否已经创建了事件容器,并且该检查已经合并。创建一个路径为fakenmc/EventRegistry.js的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);
}
});
Run Code Online (Sandbox Code Playgroud)
使用上面的类,您必须使用 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"));
...
Run Code Online (Sandbox Code Playgroud)
这段代码没有经过测试,但我想你明白了。
| 归档时间: |
|
| 查看次数: |
2979 次 |
| 最近记录: |