Skip to content

Instantly share code, notes, and snippets.

@rlogwood
Last active October 21, 2021 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rlogwood/c726eabc7f53dc9cfb59ae43eb2dc7d2 to your computer and use it in GitHub Desktop.
Save rlogwood/c726eabc7f53dc9cfb59ae43eb2dc7d2 to your computer and use it in GitHub Desktop.
Managing Stimulus state with a static helper class
import { Controller } from "@hotwired/stimulus"
import { PlaybackManager } from "../helpers/playback_manager";
export default class MusicController extends Controller {
static values = {
previewUrl: String
}
toggle() {
console.log("music previewUrlValue:(", this.previewUrlValue, ")")
PlaybackManager.toggle(this.previewUrlValue)
}
volumeUp() {
PlaybackManager.volumeUp()
}
volumeDown() {
PlaybackManager.volumeDown()
}
}
export class PlaybackManager {
static audio = null
static url = null
static currentVolume = 1
static toggle(url) {
this.#createAudioForUrlIfNeeded(url)
if (this.audio.paused) {
this.#play()
} else {
this.#pause()
}
}
static volumeUp() {
this.currentVolume += 0.25
if (this.currentVolume > 1) {
this.currentVolume = 1
}
if (this.audio) {
this.audio.volume = this.currentVolume
}
}
static volumeDown() {
this.currentVolume -= 0.25
if (this.currentVolume < 0) {
this.currentVolume = 0
}
if (this.audio) {
this.audio.volume = this.currentVolume
}
}
// private functions
static #play() {
this.audio.play()
}
static #pause() {
this.audio.pause()
}
static #createAudioForUrlIfNeeded(url) {
if (!this.audio || (this.url !== url)) {
if (this.audio && !this.audio.paused) {
this.audio.pause()
}
this.url = url
this.audio = new Audio(this.url)
this.audio.volume = this.currentVolume
console.log("Creating new audio for url:(",this.url,")")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment