Pass a variable as parameter, not its value

Asked

Viewed 104 times

2

I have the following code, and in the change function, I want to pass a variable as a parameter, not its value, and I don’t know how to do that. Because I want the function to do the "Listen" of the variable, and not of its value, so when I assign a new value to the status variable, the change event will be triggered.

let status = true;

function onChange(value, callback) {
    let aux = value;
    setInterval(() => {
        if(value != aux) {
            aux = value;
            callback();
        }
    }, 100)
}
onChange(status, () => {
    console.log('Valor Mudou');
});
status = false;
//a saída ira disparar o evento de mudança, percebendo que a variável status agora é falsa, entretanto isso não acontece pois ele está pegando o valor dela, e não a variável em si.
  • You couldn’t just use get/set?

  • @Francisco, get/set would actually solve it, but then you’d need to rewrite all the attributes that I want to do Isten, creating your getters and setters. And I didn’t want to have to rewrite, so I’m trying to do something more generic, I don’t know if it’s possible, but that would be it.

  • I think the only way you can do that is with getters and Setter or with Proxy

  • If you only have objects, you can pass their value with the reference of the original object. Then you could implement the solution that is in the question.

  • Yes @Francisco, the problem is that I am doing this for a long and old code, I would have to rewrite all the variables, the methods that use these variables, and so on. You’d have to turn them into objects, create get/set. In the end this will increase my work, this way, I would make a specific Listen for each variable: statusOnChange() and inside would say that I want to verify the value of the status variable, however as I said, I wanted to do something more generic, that could be reused. By the amount of code, at the moment get/set will not help me. :(

1 answer

3


The only way to do that is with a Setter. So when the value changes to callback will be racing again. That’s what’s behind the reactivity of Vue.js for example.

I leave an example. The idea is to have getters/setters there is there ES6 and have an array where you store the callbacks for a given variable/name. It is not possible to use variables directly because in Javascript it is not possible, but properties of an object already gives using such getters/setters.

const reactors = {}; // arrays de callbacks
const reactivos = {}; // as variáveis que vais mudar
const store = {}; // onde guardas os valores reais, isto seria uma propriedade privada de uma classe. Ou seja não deves mudar diretamente aqui, só via setter.

// define o getter/setter para "status"
function registarNome(nome, init) {
  store[nome] = init;
  if (!reactors[nome]) {
    reactors[nome] = [];
  }
  
  Object.defineProperty(reactivos, nome, {
    get() {
      return store[nome];
    },
    set(val) {
      store[nome] = val;
      reactors[nome].forEach(fn => fn(val));
    }
  });
}

// registar e inicialisar a variável
registarNome('status', true);


function onChange(nome, callback) {
  reactors[nome].push(callback);
}

// registar o auscultador de mudanças
onChange('status', (val) => {
  console.log('Valor mudou para ', val);
});

// mudanças que vão chamar a callback
reactivos.status = false;
reactivos.status = true;

Browser other questions tagged

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