Skip to content

Instantly share code, notes, and snippets.

@gnarf
Forked from tbranyen/test.js
Last active September 19, 2015 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gnarf/22afa1058031203d40c5 to your computer and use it in GitHub Desktop.
Save gnarf/22afa1058031203d40c5 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();
}
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