Sometimes, we want to unbind event handlers to bind them again later with JavaScript.
In this article, we’ll look at how to unbind event handlers to bind them again later with JavaScript.
Unbind Event Handlers to Bind Them Again Later with JavaScript
To unbind event handlers to bind them again later with JavaScript, we can use the _data
to get the event bindinds.
Then we can get the click
event binding with the click
property.
For instance, if we have:
<a id="test">test</a>
Then we write:
$(document).ready(() => {
$('#test').click((e) => {
const events = $._data($('#test')[0], 'events');
$('#test').unbind('click', events.click[0]);
});
});
to add the click event listeners with the click
method.
In the click event handler callback, we get the bindings with:
$._data($('#test')[0], 'events')
and assign it to events
.
Then we unbind the click event handler with:
$('#test').unbind('click', events.click[0]);
Then when we want to bind to the click event, we can use the events
to bind the event again.
Conclusion
To unbind event handlers to bind them again later with JavaScript, we can use the _data
to get the event bindinds.
Then we can get the click
event binding with the click
property.