Skip to content

Instantly share code, notes, and snippets.

@tbranyen
Created September 19, 2015 14:58
Show Gist options
  • Save tbranyen/64ef9ca0f4430789252c to your computer and use it in GitHub Desktop.
Save tbranyen/64ef9ca0f4430789252c to your computer and use it in GitHub Desktop.
WebComponent Backbone-events like
class CustomElement extends HTMLElement {
constructor() {
super();
}
attachedCallback() {
this.bindEvents();
}
detachedCallback() {
this.unbindEvents();
}
bindEvents() {
if (this.events) {
Object.keys(this.events).forEach(event => {
let parts = event.split(' ');
let eventName = parts[0];
let selector = parts[1];
let handler = this[this.events[eventName]];
this.addEventListener(eventName, event => {
if (selector) {
for (let el = e.target; el && el !== this; el = el.parentNode) {
if (el.matches(selector)) {
event.currentTarget = el;
handler.call(el, event);
break;
}
}
}
else {
handler.call(el, event);
}
}, true);
});
}
}
unbindEvents() {
if (this.events) {
Object.keys(this.events).forEach(event => {
let parts = event.split(' ');
let eventName = parts[0];
this.removeEventListener(eventName, this[this.events[eventName]]);
});
}
}
}
class Test extends CustomElement {
get events() {
return {
'click .event': 'cool'
};
}
cool(event) {
alert('Coolio');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment