Skip to content

Instantly share code, notes, and snippets.

@gnarf gnarf/test.js forked from tbranyen/test.js
Last active Sep 19, 2015

Embed
What would you like to do?
WebComponent Backbone-events like
class CustomElement extends HTMLElement {
constructor() {
super();
}
attachedCallback() {
this.bindEvents();
}
detachedCallback() {
this.unbindEvents();
}
handleEvent(event) {
let handler = this.events[event.type];
if (typeof handler === 'string') {
return this[handler].call(this, event);
}
if (typeof handler !== 'object') {
return;
}
let returnValue = undefined;
let selectors = Object.keys(handler);
// Find the currentTarget that first matches a selector from the handler object
for(let currentTarget = event.target; currentTarget && currentTarget !== this; currentTarget = currentTarget.parentNode) {
// If a selector matched, we want to return the returnValue
if (selectors.some(selector => {
// Ignore the '@' selector, it's fallback only
if (selector === '@') { return }
if (currentTarget.matches(selector)) {
event.currentTarget = currentTarget;
returnValue = this[handler[selector]].call(this, event);
return true;
}
})) {
return returnValue;
}
}
// Use fallback if it exists
if (handler['@'] && this[handler['@']]) {
return this[handler['@']].call(this, event);
}
},
bindEvents() {
if (this.events) {
Object.keys(this.events).forEach(event => this.addEventListener(event, this, true));
}
}
unbindEvents() {
if (this.events) {
Object.keys(this.events).forEach(event => this.removeEventListener(event, this, true));
}
}
}
class TestElement extends CustomElement {
get events() {
// Set the property so we never call the getter again
return this.events = {
'click': 'cool',
'mouseup': {
'@': 'mouseup'
'.button': 'mouseupButton'
}
};
}
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.