Skip to content

Instantly share code, notes, and snippets.

@VivaRado
Last active February 1, 2024 16:01
Show Gist options
  • Save VivaRado/7c1f2300ba8088e34c163ba4ee4c66d7 to your computer and use it in GitHub Desktop.
Save VivaRado/7c1f2300ba8088e34c163ba4ee4c66d7 to your computer and use it in GitHub Desktop.
_on (chaining, data-*event, function coupling)
EventTarget.prototype._on = (function(){
const _on = EventTarget.prototype.addEventListener;
return function(events, listener, capture, control) {
var _this = this;
var assign_data_event = function(dv){
for (var x = 0; x < dv.length; x++) {
var fname = dv[x];
var itms = document.querySelectorAll(`[${k}=${fname}]`);
var evt = k.split('-')[1];
for (var y = 0; y < itms.length; y++) {
itms[y].addEventListener(evt,function(e){
var e_data = e.currentTarget.getAttribute('data-'+evt)
var fn = control[e_data];
fn(itms[y], fname, e)
listener(e)
},capture);
}
}
}
if (typeof events === 'object' && events !== null) {
var dataEvent = events;
if ( dataEvent ) {
for (var k in dataEvent){
var e_s = k.split(" ");
if (e_s.length > 0) {
e_s.forEach(function(evt){
var dv = dataEvent[k];
assign_data_event(dv)
});
} else {
assign_data_event(k)
}
}
}
} else {
var e_s = events.split(" ");
var that = this;
// multiple events
if (e_s.length > 0) {
e_s.forEach(function(evt){
that.addEventListener(evt,function(e){
listener(e)
},capture);
});
}
}
// chaining
_on.apply(_this, arguments);
return _this;
};
})();
function controller_forgot(){
this.show_forgot_dialogue = function( target, destination, action, e ){
//
}
}
// or
/*
class controller_forgot(){
constructor(){
// might need to bind
this.show_forgot_dialogue = this.show_forgot_dialogue.bind(this)
}
show_forgot_dialogue( target, destination, action, e ){
//
}
}
*/
var _CON_forgot = new controller_forgot();
window._on('load', function (e) {
})._on({
'data-click'/*, ...*/: ['show_forgot_dialogue'/*, ...*/]}, function (e) {
console.log(e.target)
}, false, _CON_forgot );
<div data-click="show_forgot_dialogue">DIALOGUE</div>
@VivaRado
Copy link
Author

VivaRado commented Nov 4, 2023

We used to have a function that dealt with the data-*events and the overhead of jQuery to deal with the on events. Well now we removed jQuery and _on works upon vanilla addEventListener.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment