ScottyG
ScottyG

Reputation: 3410

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.

Upvotes: 1

Views: 256

Answers (1)

ScottyG
ScottyG

Reputation: 3410

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.

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");

Upvotes: 1

Related Questions