user1032531
user1032531

Reputation: 26321

Restore events removed by jQuery off()

I can remove all events from a group of elements using $('ul.links a').off().

How can I restore all removed events?

I would prefer not to use named functions when originally applying the events, and then individually adding those named functions back with on(). Maybe before applying off(), I could save all events in a data() variable?

Upvotes: 2

Views: 688

Answers (1)

A. Wolff
A. Wolff

Reputation: 74410

There is more than one option. Here is one to answer your question as stated:

//to store events
$('ul.links a').each(function () {
    $(this).data('events', $.extend(true, {}, $._data(this, 'events')));
});

//unbind events
$('ul.links a').off();

// to rebind events
$('ul.links a').each(function () {
    var $self = $(this);
    $.each($(this).data('events'), function (_, e) {
        $self.on(e[0].type, e[0].handler);
    });
});

Beware, $._data() isn't a method publicly supported, meaning it can change from version to version without prior notification.

That's said, more recommanded option would be to set some flag in events handlers to handle logic instead.

Upvotes: 4

Related Questions