简体   繁体   English

变量更新时的JavaScript回调

[英]Javascript callback on variable update

I'm currently working on a game, using HTML5 and Javascript. 我目前正在使用HTML5和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. 我不想跟踪所有Audio对象,而不必在每次设置这些按钮之一时都遍历它们,因此我声明了两个全局布尔值,即音乐和声音,都默认为true。 When they're true, their respective Audio objects play, and when false, they don't. 当它们为true时,它们各自的Audio对象播放,而为false时,它们不播放。

This is easy enough to do on object creation, with a simple if statement. 使用简单的if语句,这很容易在对象创建上完成。 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 谢谢

You can wrap the variable in an object that implements a simple event handling mechanism, here's an example: 您可以将变量包装在实现简单事件处理机制的对象中,下面是一个示例:

var variable = {
  _value: true,
  set: function(value) {
    if (value !== this._value) {
      this._value = value;
      for (var i = 0; i < this._callbacks.length; i++) {
        this._callbacks[i](value);
      }
    }
  },
  get: function() { return this._value; },

  _callbacks: [],
  onChange: function(callback) {
    this._callbacks.push(callback);
  },
  offChange: function(callback) {
    // Find the callback and remove it from the _callbacks array.
    // If !callback, this._callbacks = [];
  }
}

// Usage:
variable.onChange(function(value) { console.log(value); });

variable.set(false); // 'false' logged to the console
variable.set(false); // nothing is logged to the console

You can add multiple listeners with the onChange method. 您可以使用onChange方法添加多个侦听器。 All of them will be called when the value changes . 当值更改时,将全部调用它们。 You can remove event listeners with the offChange method. 您可以使用offChange方法删除事件侦听器。 I added it for completeness. 我添加它是为了完整性。

You can get this out-of-the-box by using a library supporting Observable Objects. 您可以使用支持Observable Objects的库来立即使用此功能。 There are many available if you look around but also include many more features that you might not need. 如果您四处看看,有很多可用的功能,但是还包括许多您可能不需要的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM