Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Created June 20, 2017 10:48
Show Gist options
  • Save WebReflection/618e314eec0bdc8b2f402876f3477a02 to your computer and use it in GitHub Desktop.
Save WebReflection/618e314eec0bdc8b2f402876f3477a02 to your computer and use it in GitHub Desktop.
// a basic delegated EventListener
class DelegatedListener {
constructor(delegated) {
this.delegated = delegated;
}
handleEvent(event) {
this.delegated['on' + event.type](event);
}
}
// components can us it directly
class Component {
constructor(node) {
node.addEventListener('click', new DelegatedListener(this));
}
onclick(event) {
event.preventDefault();
console.log(event.currentTarget, this);
}
}
// components can weakly store and access it
const delegates = new WeakMap;
class Component {
constructor(node) {
const delegated = new DelegatedListener(this);
delegates.set(this, delegated);
node.addEventListener('click', delegated);
}
onclick(event) {
event.preventDefault();
console.log(event.currentTarget, this);
}
}
// components will eventually be able
// to simply have one private delegated
class Component {
#listener;
constructor(node) {
#listener = new DelegatedListener(this);
node.addEventListener('click', #listener);
}
onclick(event) {
event.preventDefault();
console.log(event.currentTarget, this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment