What is reactivity in JavaScript?

7

I see frameworks as Angular, Vue, React, the concept of reactivity .

I'm totally uninvolved in the subject, and from what little I know, the concept of reactive programming is basically the realization of asynchronous data flow. A variable in some of those frameworks that I quoted, ends up being reactive, because as you update in the controller / component, it changes in the DOM.

But how does this really work? I inserted a snippet from how I imagine an observable function, would it be something like reactivity?

var variavel = 1

function observable (){
	setInterval(function(){
		if(variavel == 1){
    	console.log('Do Nothing...')
    } else console.log('Mudou!')
	}, 1000)
}

function Usuario(){
setInterval(function(){
	console.log('Usuario fez alguma ação que mudou a variavel')
	variavel = 2
}, 5000)
}

Usuario()
observable()
    
asked by anonymous 10.11.2017 / 13:02

1 answer

5

The way you used is not reactive, it's kind of pooling, go looking for changes and it does not scale, so it's too heavy to re-read and compare values at small time intervals.

The concept of reactivity is based on the ability of a variable to warn that it has been changed. By building a chain of reactions, a flow in the code (as you said: "asynchronous data flow"), it is possible that by changing a variable the change propagates making the application reactive.

An archaic example of reactivity would look like this:

const callbacks = {};

const VARS = {
  _foo: new Date(), // valor inicial
  get foo() {
    return this._variavel;
  },
  set foo(val) {
    this._foo = val;
    callbacks.foo.forEach(fn => fn(val));
  }
}

function observable(prop, fn) {
  if (!callbacks[prop]) callbacks[prop] = [];
  callbacks[prop].push(fn);
}

observable('foo', function(novoValor) {
  console.log('Mudou observador 1!', novoValor);
});
observable('foo', function(novoValor) {
  console.log('Mudou observador 2!', novoValor);
});


console.log('À espera...');
setInterval(function() {
  console.log('Usuario fez alguma ação que mudou a variavel')
  VARS.foo = new Date();
}, 5000)
    
10.11.2017 / 14:23