Skip to content

Instantly share code, notes, and snippets.

@ryaninvents
Last active August 29, 2015 14:15
Show Gist options
  • Save ryaninvents/c9d2db69a65fe64854ec to your computer and use it in GitHub Desktop.
Save ryaninvents/c9d2db69a65fe64854ec to your computer and use it in GitHub Desktop.
Webcomponents with events!

Creating WebComponents with custom events, via the EventEmitter library (and using lodash to assign to the prototype).

<html>
<head>
<title>Web components</title>
</head>
<body>
<x-component></x-component>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.1.0/lodash.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/EventEmitter/4.2.11/EventEmitter.min.js"></script>
<script>
var proto = Object.create(HTMLElement.prototype);
_.assign(proto, EventEmitter.prototype);
proto.name = 'Custom element'
proto.alert = function(){
alert('This is '+this.name);
};
proto.createdCallback = function(){
this.innerHTML = 'wait for it...';
console.log(this);
this.on('foo', function(){
this.innerHTML = 'Hello world!';
}.bind(this));
setTimeout(function(){
this.trigger('foo');
}.bind(this), 1000);
};
document.registerElement('x-component', {
prototype: proto
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment