How do I trigger an event when the value of a variable changes?

3

Is it possible to create a custom event so that when a variable has its value changed something happens? If yes, how to do this? For example:

In a trick game I want when the variable state changes to "bot" I want the bot to play, several functions can change the value of that variable at any time.

    
asked by anonymous 30.09.2017 / 15:55

3 answers

1

You can use setInterval() to check in time (eg every 1 second) if the variable estado has changed its value:

estado = ""; // valor inicial da variável (neste caso, vazio)
setInterval(function(){
	if(estado == "bot"){ // verifico se a variável mudou de valor
		estado = ""; // volto o valor original da variável
		console.log("vez do bot"); //mostra no console que é a vez do bot (só exemplo, pode apagar esta linha)
                // aqui vc dispara o evento
	}
	estado = "bot"; // só um exemplo de quando a variável mudar
},5000); // coloquei 5 segundos para exemplo. Talvez 1 segundo seja o ideal
Aguarde 5 segundos...
  • Within the function I put estado = "bot"; just as an example, you can delete this line.
30.09.2017 / 22:15
1

Your real problem is that " various functions can change the value of this variable at any time ". This is the real problem you have to solve.

Once you have resolved the issue of changing the variable in several possible places, you apply the Observer project pattern .

The solution would be to create a code something like this:

var Turno = (function() {
    var estado = {};
    var tipo = "player";
    var listeners = [];

    estado.adicionarListener = function(listener) {
        listeners.push(listener);
    };

    estado.getTipo = function() {
        return tipo;
    };

    estado.vezDePlayer = function() {
        tipo = "player";
        for (var i in listeners) {
            listeners[i]();
        }
    };

    estado.vezDeBot = function() {
        tipo = "bot";
        for (var i in listeners) {
            listeners[i]();
        }
    };

    return estado;
)();

And then you should swap everywhere you have this:

estado = "bot";

So:

Turno.vezDeBot();

And also change this:

estado = "player";

So:

Turno.vezDeBot();

And finally change that:

if (estado == "bot") {

So:

if (Turno.getTipo() === "bot") {

When you want something to happen as soon as it is the bot:

Turno.adicionarListener(function() {
    if (Turno.getTipo() !== "bot") return;

    // Fazer algo acontecer assim que o bot assumir a vez.
});
    
30.09.2017 / 20:44
1

As Victor said in his reply:

  

Your real problem is that "multiple functions can change the value of this variable at any time". This is the real problem you have to solve.

One way to solve is to use an object with a getter and a setter instead of the variable. The advantage is that all of your value assignments (and reads) can continue as they are (if you are already using an object), or very similar (if you are using variables yourself).

An example:

var estado = {
    set jogador(valor) {
        console.log('Aqui você intercepta a troca do valor');
    
        this._jogador = valor;
    },
    get jogador() {
        return this._jogador;
    },
    
    _jogador: 'humano'
};

console.log('jogador atual', estado.jogador);
estado.jogador = 'bot';
console.log('jogador atual', estado.jogador);
    
01.10.2017 / 04:26