I'm currently working on a game, using HTML5 and Javascript. Right now, I'm adding sound, and also want the classic 'turn music on/off' and 'turn sounds on/off' buttons. I don't want to have to keep track of all of my Audio objects, and loop over them each time I set one of these buttons, so I've declared two global booleans, music and sound, both defaulting to true. When they're true, their respective Audio objects play, and when false, they don't.
This is easy enough to do on object creation, with a simple if statement. However, if I want to change the state of the object after creation, if the user changes either setting, then it becomes an inconvenience. I'd like to be able to put a callback on the booleans, saying effectively: (pseudocode)
var music = true;
class Music() {
this.audio = new Audio(fileName);
music.onUpdate(function() {
if(music) {
this.audio.play();
} else {
this.audio.pause();
}
}
if(music) {
this.audio.play();
}
}
Furthermore, it would be even better if I could cascade these, so that several callbacks could be registered to the same variable. I appreciate that this is not something that would need to be done regularly, however is there a simple language feature I could use to implement this, before I completely rewrite this bit of the project?
Thanks