patternjavascriptMinor
Event delegation without jQuery
Viewed 0 times
withoutjquerydelegationevent
Problem
I created event delegation like concept which is present in jQuery. AFAIK, event delegation is used to register an event for an element which is supposed to be added dynamically. So, in jQuery we do the following:
So, instead of doing this event delegation in jQuery, I am doing using pure JavaScript. Here is my code:
As you can see, in the above code, I have hard coded the click event (which is fine for now)
Now, I will use the above code like this:
This is working fine but I feel like I am overdoing things here in the above created plugin.
$(document.body)
.on('click', '.main', function(){ /* code here */ });
.on('click', 'div.main', function(){ /* code here */ });
.on('click', 'div#main.main', function(){ /* code here */ });
.on('click', 'div#main.main[attr="1"]', function(){ /* code here */ });So, instead of doing this event delegation in jQuery, I am doing using pure JavaScript. Here is my code:
var sb = (function () {
var eventObject = {};
document.body.addEventListener('click', function(e){
console.dir(e.currentTarget);
var el = e.target;
var parent = el.parentElement;
while(parent !== document.body){
for(var item in eventObject){
var elements = document.querySelectorAll(item);
for(var i = 0, ilen = elements.length; i < ilen; i++){
if(el === elements[i]){
eventObject[item].call(el, e);
return;
}
}
}
el = parent;
parent = el.parentElement;
}
}, false);
return {
on: function(event, selector, callback){
eventObject[selector] = callback;
return sb;
}
}
})();As you can see, in the above code, I have hard coded the click event (which is fine for now)
Now, I will use the above code like this:
sb
.on('click', '.main', function(){ /* code here */ });
.on('click', 'div.main', function(){ /* code here */ });
.on('click', 'div#main.main', function(){ /* code here */ });
.on('click', 'div#main.main[attr="1"]', function(){ /* code here */ });This is working fine but I feel like I am overdoing things here in the above created plugin.
Solution
The one thing different between your implementation and
Another is that your
jquery.on is that jQuery allows you to bind on any element. One reason for that is performance. If on a deep tree, it would take a while for it to reach the delegate target. That's one reason jquery.live was deprecated.Another is that your
eventObject only accepts one callback per selector. If I were to register another callback under the same selector, then it would overwrite whatever was previously registered. Consider creating an array on the fly and push to it. You will need to change the way your code calls callbacks.Context
StackExchange Code Review Q#123732, answer score: 7
Revisions (0)
No revisions yet.