Reputation: 957
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
Reputation: 4452
I'm gonna try to explain it in very simple words, step by step:
<h2>Hi</h2>
element on a simple HTML pagevar h2 = document.getElemntsByTagName('h2')[0];
make two other variables first var obj = {};
and second var text = '';
this is the part that you are looking for:
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;
}
});
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
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
Reputation: 902
There is no magic, Angular for example uses zone.js, I recommend you have a read about it.
Upvotes: 0