Created
October 19, 2021 04:16
-
-
Save kzkn/7236634339ed7f95a3b5e07d7d3e0b79 to your computer and use it in GitHub Desktop.
stimulus controller lifecycle
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
import { Controller } from "@hotwired/stimulus" | |
export default class extends Controller { | |
initialize() { | |
this.log('initialize') | |
} | |
connect() { | |
this.log('connect') | |
} | |
disconnect() { | |
this.log('disconnect') | |
} | |
log(event) { | |
console.log(`exampl2#${event}`) | |
} | |
} |
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
import { Controller } from "@hotwired/stimulus" | |
export default class extends Controller { | |
initialize() { | |
this.log('initialize') | |
} | |
connect() { | |
this.log('connect') | |
this.element.textContent = "It works!" | |
} | |
disconnect() { | |
this.log('disconnect') | |
} | |
log(event) { | |
const name = this.element.dataset.name | |
console.log(`example#${event}`, name) | |
} | |
toggle() { | |
const el = document.querySelector('[data-name="ex1"]') | |
if (el) { | |
el.remove() | |
this.el = el | |
} else { | |
document.body.appendChild(this.el) | |
} | |
} | |
} |
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
<!doctype html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<link rel="stylesheet" href="main.css"> | |
<script src="bundle.js" async></script> | |
</head> | |
<body> | |
<h1 data-controller="example" data-name="ex1"></h1> | |
<!-- <h1 data-controller="example2" data-name="ex2"></h1> --> | |
<button data-controller="example" data-name="btn" data-action="example#toggle">toggle</button> | |
</body> | |
</html> |
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
# open index.html | |
example#initialize ex1 example_controller.js:19:12 | |
example#connect ex1 example_controller.js:19:12 | |
example#initialize btn example_controller.js:19:12 | |
example#connect btn example_controller.js:19:12 | |
# click button | |
example#disconnect ex1 example_controller.js:19:12 | |
# click button | |
example#connect ex1 example_controller.js:19:12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment