Kosuke Adachi
@fuyu77
2018.11.22 Meguro.rb#21
個人開発の既存のRailsプロダクトに
JSフレームワークを入れたい
$ rails webpacker:install:stimulus
<%= javascript_pack_tag 'application' %>
をHTMLのheadタグ内に追加controller.target
event->contoroller#method
html
hello_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "name", "output" ]
greet() {
this.outputTarget.textContent = `Hello, ${this.nameTarget.value}!`
}
}
html
hello_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
initialize() {
console.log("initialize")
// initialize
// connect
const element = document.getElementById("hello")
element.remove()
// disconnect
document.body.appendChild(element)
//connect
}
connect() {
console.log("connect")
}
disconnect() {
console.log("disconnect")
}
}
html
data-hello-index
を持っていたらtrue, 持っていなかったらfalsedata-hello-index
の値をString型で返すdata-hello-index
に値をセットするhtml
🐵
🙈
🙉
🙊
css
.slide {
display: none;
}
.slide.slide--current {
display: block;
}
slideshow_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "slide" ]
initialize() {
this.showCurrentSlide()
}
next() {
this.index++
}
previous() {
this.index--
}
showCurrentSlide() {
this.slideTargets.forEach((el, i) => {
el.classList.toggle("slide--current", this.index == i)
})
}
get index() {
return parseInt(this.data.get("index"))
}
set index(value) {
this.data.set("index", value)
this.showCurrentSlide()
}
}
connect()
とdisconnect()
が具体的にどう役立つのかつかめなかった