实用地测试特定事件处理程序(函数)是否使用jQuery绑定到对象的事件 [英] Pragmatically test if specific event handler(function) is bound to an object's event using jQuery
问题描述
我正在寻找一种方法来专门测试特定事件是否将某个处理程序(函数)绑定到特定对象.
I was looking for method to specifically test if a certain handler(function) was bound to specific object on a specific event.
我要解决的问题是我想将处理程序绑定到对象卸载事件,但是我想要一种方法来测试它是否已经绑定,因此我没有两次绑定它.
The problem I am trying to solve is I want to bind a handler to an objects unload event but I wanted a way to test if it was already bound so I did not bind it twice.
推荐答案
以下是对我有用的解决方案.我使用了这个stackoverflow答案( https://stackoverflow.com/a/2518441/2512022 )创建以下函数来测试对象是否具有绑定到特定事件的特定处理程序.
Here is a solution that worked for me. I used this stackoverflow answer (https://stackoverflow.com/a/2518441/2512022) to create the following function to test if a object has a specific handler bound to a specific event.
此函数将对象,事件名称和处理程序函数名称作为输入参数,如果该函数绑定了传入对象上的事件,则将返回true/false.
This function take a Object, Event Name, and handler function name as input parameters and will return true/false if the function is bound the event on the object passed in.
function testHandler(obj, sEvent, sHandlerName)
{
var retVal = false;
// Get all events bound to object
var windowEvents = jQ._data(obj, "events");
// Get all handlers for a specific event
var handlers = windowEvents[sEvent];
jQ(handlers).each(function() {
// Using passed name to see if there is a match
if(this.handler.name === sHandlerName)
{
retVal = true;
return;
}
});
return retVal;
}
然后按如下所示调用函数.
Then call the function as follows.
// Test if there is a beforeclose() handler bound to the window objects
// "beforeunload" event
testHandler(window, "beforeunload", "beforeclose");
您甚至可以测试事件是否附加了匿名处理程序.在此"下方的调用中引用了一个按钮,我们正在测试按钮单击事件是否附加了匿名处理
You could even test if there is on anonymous handler attached to an event. In the call below "this" references a button, and we are testing if there is an anonymous hanlder attached to the buttons click event
testHandler(this, "click", "anonymous");
这篇关于实用地测试特定事件处理程序(函数)是否使用jQuery绑定到对象的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!