4

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??

6

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

this is actually a well-documented library. And it has support for my favourite TypeScript :) .
-1

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.

1 Comment

@Dimitriy Kovalenko It's also that React has a setState(state) function which is easy to find out when it's fired. Other frameworks like Vue.js and Knockout.js do actually listen on variable change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.