Skip to content

Instantly share code, notes, and snippets.

@FremyCompany
Last active November 19, 2021 16:03
Show Gist options
  • Save FremyCompany/6ee7b1b66e462b626020 to your computer and use it in GitHub Desktop.
Save FremyCompany/6ee7b1b66e462b626020 to your computer and use it in GitHub Desktop.
Namespaces events without jQuery
// once in the headers
defineMetaEvent('Namespace','Click');
// then when you need it
document.body.onNamespaceClick.add(function(e) { /*...*/ });
document.body.onNamespaceClick.clear();
function defineMetaEvent(namespace,realEvent) {
var eventName = 'on'+namespace+realEvent;
var realEventLw = realEvent.toLowerCase();
Object.defineProperty(Element.prototype, eventName, {get:function() {
//
// where we store the handlers of the meta event:
//
var el = this;
var handlers = [];
//
// the interface we expose to the world
//
var wrapper = {
//
// add a new handler
//
add: function(f) {
var newLength = handlers.unshift(f);
if(newLength==1) { rebind(); }
},
//
// remove an existing handler
//
remove: function(f) {
var index = handlers.indexOf(f); if(index>=0) {
handlers.splice(index, 1);
if(handlers.length==0) { unbind(); }
}
},
//
// remove all handlers
//
clear: function() {
handlers.length=0; unbind();
}
};
//
// the function we use for addEventListener()
// it calls the handlers, simply
//
var metaHandler = function(e) {
var v = true;
for(var i=handlers.length; i--;) {
try { v = !!handlers[i].call(el,e) && v; }
catch(ex) { setTimeout(function() { throw ex; },0); }
}
return v;
}
//
// binding metaHandler to the real event
//
var unbind = function() {
el.removeEventListener(realEventLw, metaHandler);
}
var rebind = function() {
el.addEventListener(realEventLw, metaHandler, false);
}
//
// caching the wrapper
//
Object.defineProperty(el, eventName, {value:wrapper});
return wrapper;
}});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment