Skip to content

Instantly share code, notes, and snippets.

@Fil
Last active February 1, 2018 16:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fil/be9e7ba360e2f6797e6071351fa122a6 to your computer and use it in GitHub Desktop.
Save Fil/be9e7ba360e2f6797e6071351fa122a6 to your computer and use it in GitHub Desktop.
Hello stimulusjs
license: mit
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
.slide {
display: none;
font-size: 180px;
}
.slide.slide--current {
display: block;
}
</style>
<head>
<body>
<div data-controller="slideshow">
<button data-action="slideshow#previous">←</button>
<button data-action="slideshow#next">→</button>
<div data-target="slideshow.slide" class="slide slide--current">🐵</div>
<div data-target="slideshow.slide" class="slide">🙈</div>
<div data-target="slideshow.slide" class="slide">🙉</div>
<div data-target="slideshow.slide" class="slide">🙊</div>
</div>
<div data-controller="hello">
<input data-target="hello.name" type="text">
<button data-action="click->hello#greet">Greet</button>
</div>
<p/>
<div>Using <a href="https://github.com/stimulusjs/stimulus">stimulusjs</a></div>
<script src="https://unpkg.com/stimulus/dist/stimulus.umd.js"></script>
<script src="https://unpkg.com/d3"></script>
<script>
(function() {
const application = Stimulus.Application.start();
application.register(
"hello",
class extends Stimulus.Controller {
greet() {
d3.select("p").html(`Hello, ${this.name}!`);
}
get name() {
return this.targets.find("name").value;
}
}
);
application.register(
"slideshow",
class extends Stimulus.Controller {
initialize() {
this.render();
}
next() {
if (this.index < this.lastIndex) {
this.index++;
}
}
previous() {
if (this.index > 0) {
this.index--;
}
}
render() {
this.slideElements.forEach((element, index) => {
element.classList.toggle("slide--current", index == this.index);
});
}
get index() {
if (this.data.has("index")) {
return parseInt(this.data.get("index"));
} else {
return 0;
}
}
set index(value) {
this.data.set("index", value);
this.render();
}
get lastIndex() {
return this.slideElements.length - 1;
}
get slideElements() {
return this.targets.findAll("slide");
}
}
);
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment