Вот версия на основе прототипа
Document.prototype.on = function(event, target = null, callBack){
this.addEventListener(event, function(event){
let len = target.length, i = 0;
while(i < len){
if(event.target === target[i]){
callBack.call(target[i], event);
}
i ++;
}
}, false);
};
Использование похоже на jQuery:
let btns = document.getElementsByTagName('button');
document.on('click', btns, function(event){
console.log(this.innerText)
});
И пример ниже:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body bgcolor="#000">
<button>hello1</button>
<button>hello2</button>
<script type="text/javascript">
Document.prototype.on = function(event, target = null, callBack = function(){}){
this.addEventListener(event, function(event){
let len = target.length, i = 0;
while(i < len){
if(event.target === target[i]){
callBack.call(target[i], event);
}
i ++;
}
}, false);
};
//example of usage
let btns = document.getElementsByTagName('button');
document.on('click', btns, function(t){
alert(this.innerText);
})
//add elements after delegating an event
let newBtn = document.createElement('button');
newBtn.innerText = 'btnNew';
document.body.appendChild(newBtn);
//delay to create
setTimeout(function(){
let newBtn = document.createElement('button');
newBtn.innerText = 'another btnNew';
document.body.appendChild(newBtn);
},2000);
</script>
</body>
</html>