jquery / jquery/learn.jquery.com
Expand events tutorials to cover cases where bound elements are removed and re-added.
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 915
- Forks
- 471
- PR merge metrics
- No merged PRs in 30d
Description
Originally filed in jquery/api.jquery.com#632.
There seems to be pretty regular confusion surrounding the notion that event bindings break if the element you bound to was removed from the document (via, say, .remove()) and then re-added (like when you create a new element with $()).
The specific issue is that people think that simply using a delegated listener is enough - e.g.:
$('.someDiv').on('click', '.someChild', function() {
$('.someDiv').remove();
});
They then later re-add $('.someDiv') and expect this to work because the handler is technically bound to an element that exists at the time of binding - it just happened to be removed and re-added.
The .remove() docs helpfully explain that:
In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use
.detach()instead.
This is fine, except that a lot of people aren't going to think to go to docs for .remove() while reading about events. This also doesn't cover cases where somebody ran something like .html('<span>no cookie for you</span>') on a parent of the bound node, wiping it out.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the existing events tutorials and the .remove() documentation, using the delegated .on('click', '.someChild', ...) example as the motivating case. Expand the tutorials to explain what happens when bound elements are removed and re-added, including removal through .html(), and make clear when .detach() preserves handlers.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100