4
\$\begingroup\$

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:

$(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.

200_success
146k22 gold badges190 silver badges478 bronze badges
asked Mar 24, 2016 at 9:24
\$\endgroup\$

1 Answer 1

7
\$\begingroup\$

The one thing different between your implementation and 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.

answered Mar 24, 2016 at 12:24
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.