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

Asked

Viewed 1,263 times

3

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

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

  • Give us a scenario where you need to use this, so it’s easier to give us an answer that fits what you want.

  • 1

    That’s a XY problem. The solution you want to apply is not ideal for your problem. Try to be more specific and detailed, preferably by placing a code block where you want to use it.

  • wish there was something like when (status == "bot") knife x

3 answers

2

Like Victor said in his answer:

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

One of the ways to solve is to use an object with a getter and a Setter instead of the variable. The advantage is that all your value assignments (and readings) can continue as they are (if you’re already using an object), or very similar (if you’re using variables at all).

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);

1

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

After solving the problem of the variable being changed in several possible locations, you apply the Observer design standard.

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 must trade all the places that have it:

estado = "bot";

That’s why:

Turno.vezDeBot();

And also change that:

estado = "player";

That’s why:

Turno.vezDeBot();

And finally change that:

if (estado == "bot") {

That’s why:

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

When you want something to happen as soon as it’s the bot’s turn:

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

    // Fazer algo acontecer assim que o bot assumir a vez.
});

1


It is possible to use a setInterval() to keep checking of time to time (ex. every 1 second) if the variable estado change of 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 placed estado = "bot"; just as an example, you can delete this line.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.