This is really just for me...
August 11, 2018, 12:21 pm

So you want to write in vanilla Javascript. But you've definitely noticed it's missing some shit. And if you haven't noticed, it's because you never really learned how to write jQuery.

One of the major reasons I will probably not give up jQuery any time soon, is because of event delegation. Event delegation is a great way to make event listeners that don't require an existing element yet. This lets us set up events for any element that MIGHT exist some time in the future.

Well here's a small function to add super basic event delegation for a space separated string of classes to your code setup.

function delegateEvent(delegate,event,target,callback){ var targets = target.split(" "); delegate.addEventListener(event, function (e) { targets.forEach(function(o){ if ( e.target.classList.contains(o) ) callback.apply(e.target,[e]); }); }, false); }

It's pretty simple. But it's a major relief to have this written out even for myself.

You could even take this one step further. You could add a delegate function to all object prototypes. This is technically a bad idea for big projects, but you shouldn't be writing very much code like this for that size of a project anyways. You should be using some framework or library.

Object.prototype.delegate = function(event,target,callback){ this.addEventListener(event, function (e) { var targets = document.querySelectorAll(target); [].forEach.call(targets,function(o){ if ( e.target == o ) callback.apply(e.target,[e]); }); }, false); }

This even gives us the ability to create query selectors instead of just class lists like the previous example.