Currently in the process of developing a custom JS library similar to jQuery, I've encountered a stumbling block.
I have successfully created an event delegation function intended for a simple click event.
While working within this prototype section, I'm attempting to execute some logic (such as adding a class), but I'm facing issues with the 'this' keyword. Specifically, I need to be able to add a class to the clicked element.
Constructor.prototype.on = function (eventName , elementSelector, callback) {
document.addEventListener(eventName, function(e) {
for (var target = e.target; target && target != this; target = target.parentNode) {
if (target.matches(elementSelector)) {
callback.call(target, e);
break;
}
}
}, false);
};
// X represents the plugin
X('body').on('click','.someClass',function(){
X(this).addClass('clicked');// unfortunately, this won't work
});