-
-
Save gnarf/22afa1058031203d40c5 to your computer and use it in GitHub Desktop.
WebComponent Backbone-events like
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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