Last active
October 22, 2017 23:47
-
-
Save beefchimi/a0de212eba2f74441b64339a0efa2bb4 to your computer and use it in GitHub Desktop.
SoundToggle class
This file contains hidden or 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
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