Skip to content

Instantly share code, notes, and snippets.

@fernandofleury
Created February 3, 2016 14:36
Show Gist options
  • Save fernandofleury/ce4c6d4b218602223863 to your computer and use it in GitHub Desktop.
Save fernandofleury/ce4c6d4b218602223863 to your computer and use it in GitHub Desktop.
component handling javascript
import emitter from '../utils/emitter';
const foo = (element) => {
let result = element.querySelector('[data-all="result"]');
let counter = 0;
emitter.on('counter', () => result.innerHTML = ++counter);
};
export default foo;
import emitter from '../utils/emitter';
class Counter {
constructor(element) {
this.element = element;
this.counter = 0;
this.button = this.element.querySelector('[data-counter="button"]');
this.result = this.element.querySelector('[data-counter="result"]');
this.listeners();
}
listeners() {
this.button.addEventListener('click', () => {
this.result.innerHTML = ++this.counter;
emitter.emit('counter');
});
}
}
const counter = (element) => {
return new Counter(element);
};
export default counter;
(function() {
let components = document.querySelectorAll('[data-component]');
Array.prototype.forEach.call(components, (node) => {
let component = node.getAttribute('data-component');
require(`./components/${component}`).default(node);
});
})();
import Emitter from 'events';
export default new Emitter();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Frontend Architecture Spec</title>
</head>
<body>
<div data-component="counter">
<button data-counter="button" type="button">Click me</button>
<div data-counter="result"></div>
</div>
<div data-component="counter">
<button data-counter="button" type="button">Click me</button>
<div data-counter="result"></div>
</div>
<div data-component="all">
All counter components have been clicked:
<div data-all="result">0 times</div>
</div>
<script src="bundle.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment