Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.