What is reactivity in Javascript?

Asked

Viewed 1,726 times

11

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

I’m totally naive on the subject, and as far as I know, the concept of reactive programming is basically performing asynchronous data flow. A variable in any of these frameworks which I mentioned, turns out to be reactive, because as you update the controller/component, it changes the DOM.

But how does it really work? I inserted a snippet how I imagine a observable working, would be something of that kind consisting of 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()

  • 1

    Thanks for Edit, @Stormwind

1 answer

10


The way you used it is not reactive, it is kind of pooling, go looking for changes and this does not scale, ie it is very heavy to be re-read and compare values in small time intervals.

The concept of reactivity is based on the ability of a variable to warn that it has been changed. Building a chain of reactions, a stream in the code (like 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 be 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)

  • Very well explained! Thank you @Sergio :) !!

Browser other questions tagged

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