Matas Vaitkevicius
Matas Vaitkevicius

Reputation: 61401

How to find delegated event listeners?

Normally to get listeners on that DOM node I am using

$('selector').data('events');

However this does not show event listeners that are being add via delegation, e.g

$(document).on('click', 'selector', handlerFunction) 

One obvious way is to traverse up the DOM tree and look if any of parents are delegating events to element at hand, by concurrently calling $('selector').parent().data('events') until no parent can be found, however this does not strike me as very efficient or standard way of doing things, and I think of it this sort of problem is too common not to have a better solution.

How to find all the event listeners including delegated ones?

Upvotes: 0

Views: 347

Answers (1)

Matas Vaitkevicius
Matas Vaitkevicius

Reputation: 61401

ATM I am using functions below, not to elegant - but saves me quite some time.

var getAllEventListeners = function (options) {
    if (options.internalArr == undefined)
        options.internalArr = [];
    if (options.elements.data('events') != undefined) {
        options.internalArr.push({
            elements: options.elements,
            events: options.elements.data('events')
        });
    }
    if (options.elements.parent().length != 0) {
        getAllEventListeners({
            elements: options.elements.parent(),
            internalArr: options.internalArr
        });
    }
}

var findAllListeners = function (selector) {
    var opt = {
        elements: $(selector),
        internalArr: []
    };
    getAllEventListeners(opt);
    return opt.internalArr;
}

Upvotes: 0

Related Questions