durisvk
durisvk

Reputation: 957

How does Vue.js, React.js, Angular.js actually work

This is some sort of question from curiossity.

The question is:

How does these Client-side frameworks work, let me explain.

I am working with javascript for more than 5 years. And I don't understand one thing. How do they know when the variable (for example title) variable value changes???.

I would do it like this:

function onTitleChange(title) { //do some stuff }
let title = "This is some title"
let lastTitle = title;
setInterval(() => {
    if(lastTitle !== title) {
        onTitleChange(title);
        lastTitle = title
    }
}, 10);

Is this how they all work? Is this how the Vue.js knows when the variable value changes? If not, what sort of magic do they use to know when a variable value changes??

Upvotes: 4

Views: 516

Answers (3)

Soorena
Soorena

Reputation: 4452

I'm gonna try to explain it in very simple words, step by step:

  1. make a <h2>Hi</h2> element on a simple HTML page
  2. open browser console and store DOM element in a variable: var h2 = document.getElemntsByTagName('h2')[0];
  3. make two other variables first var obj = {}; and second var text = '';

    this is the part that you are looking for:

  4. instead of simply assigning obj.text = text we declare getter setter's for obj.text attribute so that whenever we set new value to obj.text the corresponding DOM element changes too.

    Object.defineProperty(obj, 'text', {
        get: function () {
            return text;
        },
        set: function (newvalue) {
            text = newvalue;
            h2.innerHTML = text;
        }
    });
    
  5. now go on and change obj.text value : obj.text = "Hello again"

for more information check this page out.

all the codes available at : JSfiddle

Upvotes: 2

Dmitriy Kovalenko
Dmitriy Kovalenko

Reputation: 3624

Little about React - its not actually listen to changes of the js objects, because of it only call render methods of components, if shouldComponentUpdate() (default it use reference equality of the component state) return true, and check if returned VirtualDOM is equal to the real DOM.

Because of it - its much more faster then Angular, which use many of listeners and equality checkers for watching updates.

Upvotes: -1

Shahar Galukman
Shahar Galukman

Reputation: 902

There is no magic, Angular for example uses zone.js, I recommend you have a read about it.

Upvotes: 0

Related Questions