Created
September 19, 2015 14:58
-
-
Save tbranyen/64ef9ca0f4430789252c 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(); | |
} | |
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