2

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?

user1032531
  • 24,767
  • 68
  • 217
  • 387

1 Answers1

4

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.

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • I was planning on using `data()` (https://api.jquery.com/data/), not `$._data()`. Is the former not a publicly supported method which could change from version to version without prior notification? – user1032531 May 10 '15 at 14:38
  • `$._data()` is used only internally but this is the only way i know to retrieve jq events bound to any specific element. There is in fact three `datas` method type in jQuery, `$.fn.data` (public) `$.data` (internal) and `$._data` (internal) – A. Wolff May 10 '15 at 14:47
  • Gotcha! Will go with the flag method. Just an observation, but http://stackoverflow.com/a/24502972/1032531 indicates to use `$('#submitBtn').prop('disabled',true) ` to disable the events. Doesn't work as far as I could tell. – user1032531 May 10 '15 at 14:50
  • 1
    `.prop('disabled',true)` is used to set boolean attribute disbaled. An element with disabled attribute doesn't respond to any (mouse?) events. BUT this is only for elements of type `:input` as textbox, textarea, button, etc... The attribute disabled on anchor tag (A) has no effect. From w3c DOC: `The following elements support the disabled attribute: BUTTON, INPUT, OPTGROUP, OPTION, SELECT, and TEXTAREA.` http://www.w3.org/TR/html401/interact/forms.html#h-17.12.1 – A. Wolff May 10 '15 at 14:54