dojo:哪些事件附加到元素?

问题描述 投票:2回答:2

如何使用dojo接收附加到元素的所有事件?

dojo.query('#mydiv') // which events does #mydiv has?
javascript-events dojo
2个回答
4
投票

要获取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的子类来隐藏恼人的检查以查看是否已创建事件容器,并且此检查已合并。使用此路径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);
    }
});

使用上面的类,您将不得不使用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"));
...

这段代码没有经过测试,但我认为你明白了。


1
投票

如果它仅用于调试目的。您可以在您的firebug控制台中尝试dijit.byId("myId").onClick.toString();,即使该函数是匿名的,您也可以查看整个onclick代码,您可以查看匿名内容的内容。

© www.soinside.com 2019 - 2024. All rights reserved.