Created
October 6, 2017 12:53
-
-
Save absent1706/4bae11709ec1857755ff501a7f798170 to your computer and use it in GitHub Desktop.
DIY jQuery delegated events handling like $(document).on('click', '.child', handler)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script> | |
/* Core function which does event delegation like jQuery http://www.qopy.me/MpAEDJZiQKutDbKGuOEdQA | |
* Writing | |
* addDelegatedEventListener(parent, eventName, childSelector, handler) | |
* | |
* Is absolutely equivalent to writing jQuery's code: | |
* $(parent).on(eventName, childSelector, handler) | |
*/ | |
function addDelegatedEventListener(parent, eventName, childSelector, handler) { | |
var proxyHandler = function(event) { | |
var thisHandler = arguments.callee; // current function | |
// We should determine whether initial event target is child we need. | |
// For that, we check that: | |
// 1) target is inside container; | |
// 2) target can be matched by childSelector | |
if (parent.contains(event.target) && event.target.matches(thisHandler.childSelector)) { | |
handler(event); | |
} | |
}; | |
proxyHandler.childSelector = childSelector; | |
parent.addEventListener(eventName, proxyHandler); | |
} | |
</script> | |
</head> | |
<body> | |
<h1>Delegated events demo</h1> | |
<button onclick="loadMoreProducts()">Load more products</button> | |
<hr> | |
<button class="product">Product 1 info</button> | |
<hr> | |
<button class="product">Product 2 info</button> | |
<hr> | |
<script> | |
// emulate new products loading | |
function loadMoreProducts() { | |
// emulate AJAX request | |
setTimeout(function(){ | |
var newProduct = document.createElement('button'); | |
newProduct.innerHTML = 'Product 3 info'; | |
newProduct.classList.add('product'); | |
document.body.appendChild(newProduct); | |
document.body.appendChild(document.createElement('hr')); | |
}, 500); | |
} | |
// With our trick, handler will work even on dynamically loaded elements! | |
// It's equivalent to JQuery: | |
// $(document).on('click', '.product', function...) | |
addDelegatedEventListener(document, 'click', '.product', function(event) { | |
alert('This is ' + event.target.innerHTML); | |
}); | |
/* Below is standard way to handle this stuff. | |
* Uncomment below code and notice that handler | |
* will NOT work on dynamically loaded elements | |
*/ | |
// document.querySelectorAll('.product').forEach(function(el){ | |
// el.addEventListener('click', function(event) { | |
// alert('This is ' +event.target.innerHTML); | |
// }); | |
// }); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment