Overview
There was a very valuable article that expressing React features with jQuery, but now it is no longer invisible, so I recapitulate it with my own interpretation.
This article focuses on State Management, which is one of the important concepts in Frontend Frameworks (React, Vue.js). Note that Plain Javascript is used not jQuery.
Original code
<span id="colored-counter">0</span>
<input id="color" placeholder='#000'></input>
<input type="button" id="count_button" value='add' />
<script>
document.querySelector("#color").onkeyup = function() {
document.querySelector('#colored-counter').style.color = this.value;
}
document.querySelector("#count_button").onclick = function() {
const oldValue = document.querySelector('#colored-counter').innerHTML;
const newValue = 1 + Number(oldValue);
document.querySelector('#colored-counter').innerHTML = newValue;
}
</script>
If you want it to work, copy and paste should work.
The functions are as follows.
- Pressing a button increments the count
- Entering a color code changes the color of the count
I will rewrite this using the State Management approach.
Code with the State Management approach
<span id="colored-counter">0</span>
<input id="color" placeholder='#000'></input>
<input type="button" id="count_button" value='add' />
<script>
let state = {color: '', value: 0};
function setState() {
document.querySelector('#colored-counter').style.color = state.color;
document.querySelector('#colored-counter').innerHTML = state.value;
}
document.querySelector('#color').onkeyup = function () {
state.color = this.value;
setState();
}
document.querySelector('#count_button').onclick = function () {
state.value++;
setState();
}
</script>
The functionality is the same as in the code above.
What I want to express here is the follows.
- Avoid manipulating the DOM directly in various codes (gather
.innerText
and.style
, etc in one place) - Manage the DOM state with a Hash variable.
- The screen rendering will be updated based on the variable.
This concept should be roughly the same for both React and Vue.js.
This is an introduction to a concept that I want people who can't or don't want to use Frontend Frameworks to know about. And it is not simply "jQuery and Plain JS can do it too, so let's do it" (although it is not absolutely prohibited to incorporate it in jQuery or Plain JS).
Top comments (0)