Skip to content

Instantly share code, notes, and snippets.

@beefchimi
Last active October 22, 2017 23:47
Show Gist options
  • Save beefchimi/a0de212eba2f74441b64339a0efa2bb4 to your computer and use it in GitHub Desktop.
Save beefchimi/a0de212eba2f74441b64339a0efa2bb4 to your computer and use it in GitHub Desktop.
SoundToggle class
function disabledAudio() {
return null;
}
export default class SoundToggle {
constructor(activator, sounds) {
this.activator = activator;
this.sounds = sounds;
this.keys = Object.keys(sounds);
this.backups = {};
this.label = {
disable: this.activator.dataset.labelDisable,
enable: this.activator.dataset.labelEnable,
};
}
init() {
this._setState(this.activator.dataset.enabled);
this.activator.addEventListener('click', this.toggle.bind(this));
}
toggle() {
const newState = (this.activator.dataset.enabled === 'true') ? 'false' : 'true';
this._setState(newState);
if (Object.keys(this.backups).length === 0) {
this._backupPlayMethods();
}
this.keys.forEach((sound) => {
this.sounds[sound].play = (this.enabled) ? this.backups[sound] : disabledAudio;
});
}
_backupPlayMethods() {
this.keys.forEach((sound) => {
this.backups[sound] = this.sounds[sound].play;
});
}
_setState(state) {
this.enabled = (state === 'true');
this.activator.dataset.enabled = this.enabled;
this.activator.textContent = (this.enabled) ? this.label.disable : this.label.enable;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment