Last active
October 21, 2021 22:03
-
-
Save rlogwood/c726eabc7f53dc9cfb59ae43eb2dc7d2 to your computer and use it in GitHub Desktop.
Managing Stimulus state with a static helper class
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" | |
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() | |
} | |
} |
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
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