Table of Contents
Yes, that’s it Reasons, let's take a look at why
Implementing a relatively complex UI using native (JS)
Responsive UI saves everything
How does the framework work?
What about Web components?
Do it yourself and have enough food and clothing
Заключение
Home Web Front-end JS Tutorial 2018 js review: The fundamental reasons for the existence of the framework are these

2018 js review: The fundamental reasons for the existence of the framework are these

Jul 25, 2018 am 09:53 AM

The main problem solved by modern js frameworks is keeping the UI and state in sync. Writing complex, efficient, and maintainable UI interfaces using native JavaScript is nearly impossible. I have seen many, many people blindly use (front-end) frameworks such as React, Angular or Vue, etc. These frameworks provide a lot of interesting stuff, but usually people (think) use frameworks because:

  • They support componentization;

  • They have strong community support;

  • They have many (framework-based) third-party libraries to solve Problem;

  • They have a lot of (good) third party components;

  • They have browser extensions to help with debugging;

  • They are suitable for single-page applications.

But these are not the fundamental reasons for using the framework.

The most essential reason is:

2018 js review: The fundamental reasons for the existence of the framework are these

(It is very difficult to synchronize UI and state)

Yes, that’s it Reasons, let's take a look at why

Suppose you are designing a web application where users can invite others (to participate in an event) by sending a group email. The UX/UI designer designed it as follows: (before the user fills in any email address,) there is a blank state and adds some help information for this; (after the user fills in the email address,) the email address is displayed on the right side of each address There is a button for deleting the corresponding address.

2018 js review: The fundamental reasons for the existence of the framework are these

The status of this form can be designed as an array, which contains several objects. The objects consist of email addresses and unique identifiers. At the beginning, the array is empty. After (the user) enters their email address and presses Enter, add an item to the array and update the UI. When the user clicks the delete button, delete the email address (corresponding to the array) and update the UI. Did you feel it? Every time you change state, you need to update the UI.

(You might say:) So what? Well, let’s see how to implement it without a framework:

Implementing a relatively complex UI using native (JS)

The following code nicely illustrates the implementation using native JavaScript The amount of work required for a relatively complex UI is similar to the amount of work required to use a classic library like jQuery.

In this example, HTML is responsible for creating static pages, and JavaScript dynamically changes (DOM structure) through <span class="pln" style="color:rgb(72,72,76);">document</span><span class="pun" style="color:rgb(147,161,161);">.</span><span class="pln" style="color:rgb(72,72,76);">createElement</span>. This leads to the first problem: the JavaScript code related to building UI is not intuitive and easy to read. We divide UI building into two parts (Translator's Note: It should refer to HTML and JavaScript parts). Although we use <span class="pln" style="color:rgb(72,72,76);">innerHTML</span>, readability is enhanced, but performance (of the page) is reduced, and CSRF vulnerabilities may exist. We can also use a template engine, but if we modify the DOM in a large area, we will face two problems: low efficiency and the need to rebind the event handler.

But this is not the biggest problem (without using a framework). The biggest problem is having to (manually) update the UI every time the state changes. This requires a lot of code to change the UI every time the status is updated. When adding an email address, it only takes two lines of code to update the status, but thirteen lines of code to update the UI. (In this case) We've made the UI (interface and logic) as simple as possible! !

2018 js review: The fundamental reasons for the existence of the framework are these

The code is difficult to write and difficult to understand. What's even more troublesome is that it is very fragile. Suppose we need (add) the function of synchronizing server data to a list of email addresses, and we need to compare the difference between the results returned by the server and the data in the array. This involves comparing the identity and content of all data, which may require retaining a copy of data with the same identity but different content in memory (when modified by the user).

In order to change the DOM efficiently, we need to write a lot of point-to-point (Translator's Note: refers to state to UI) code. ButAs soon as you make a small mistake, the UI and state will no longer be in sync: (possibly) missing or wrong information, no longer responding to user operations, or worse, triggering The wrong action was taken (such as clicking the delete button and then deleting a non-corresponding item).

So keeping the UI in sync with the state requires writing a lot of tedious and very brittle code.

Responsive UI saves everything

2018 js review: The fundamental reasons for the existence of the framework are these

So, (the reason for using the framework is) not because of the community, not because of the tools, not because of the ecology, not because of the third Third-party libraries...

So far, the biggest improvement of the framework is that it provides (for us) a reliable guarantee of synchronization between the internal state of the application and the UI.

As long as you know some (specific) rules of a specific framework (such as immutable state), it's almost (can be used normally).

We only need to define the UI interface once, and no longer need to write specific UI code for each operation. At the same time, each same state has the same output (Translator's Note: Refers to UI consistency): When the state changes, the framework automatically updates the (corresponding) view.

How does the framework work?

Based on two basic strategies:

  • Re-render the entire component, like React. When the state in a component changes, the (new) DOM structure is calculated in memory and compared with the existing DOM structure. In fact, it's very expensive. Therefore, the real DOM is mapped to the virtual DOM, and by comparing the differences between the virtual DOM before and after the state change, the changes are calculated and then the real DOM structure is changed. This process is called reconciliation.

  • #Monitor changes via (added) observers like Angular and Vue.js. The properties of the application state are monitored, and when they change, only the DOM elements that depend on the (changed) properties are re-rendered.

What about Web components?

Many times, people compare React, Angular and Vue.js (frameworks such as) with Web components. This clearly shows that people don't understand the biggest benefit these frameworks provide: keeping the UI in sync with the state. Web components do not provide this synchronization mechanism. Itonlyprovides a template tag, but it does not provide any coordination mechanism (between state and UI). If you want to keep the UI synchronized with the internal state when using Web components in your application, you need to do it manually (developer), or use something like Stencil.js (Internally the same as React , using libraries like Virtual DOM).

Let us be clear: the huge potential of the framework is not reflected in componentization, but in keeping the UI and state synchronized. Web components do not provide related functionality, you must solve the (synchronization) problem manually or use a third-party library. It's basically impossible to write complex, efficient, and easy-to-maintain UI interfaces using native JavaScript. This is the fundamental reason why you need to use a modern JavaScript framework.

Do it yourself and have enough food and clothing

If you are keen on understanding the underlying principles, you would like to know the specific implementation of virtual DOM. So, why not try to rewrite the native UI using only virtual DOM without using a framework?

This is the core of the framework, the base class for all components.

2018 js review: The fundamental reasons for the existence of the framework are these

Here is the rewritten AddressList component (using babel to support JSX conversion).

2018 js review: The fundamental reasons for the existence of the framework are these

Теперь пользовательский интерфейс является декларативным и мы не используем никакой фреймворк. Мы можем добавить новую логику для изменения состояния по своему желанию без написания дополнительного кода для синхронизации пользовательского интерфейса. Проблема решена!

За исключением обработки событий, это похоже на приложение React, верно? У нас есть <span class="pln" style="color:rgb(72,72,76);">haverender</span><span class="pun" style="color:rgb(147,161,161);">()</span>, <span class="pln" style="color:rgb(72,72,76);">comComponentDidMount</span><span class="pun" style="color:rgb(147,161,161);">()</span>, <span class="pln" style="color:rgb(72,72,76);">setState</span><span class="pun" style="color:rgb(147,161,161);">()</span> и так далее. Как только вы решите проблему синхронизации пользовательского интерфейса и состояния внутри приложения, все естественным образом сложится (компоненты формы).

Полный исходный код можно найти в этом репозитории Github.

Заключение

  • Основная проблема, которую решают современные js-фреймворки, — это синхронизация пользовательского интерфейса с состоянием.

Написание сложных, эффективных и удобных в обслуживании интерфейсов пользовательского интерфейса с использованием встроенного JavaScript практически невозможно.

#Веб-компоненты не решают проблемы синхронизации.

Не сложно использовать существующую виртуальную библиотеку DOM для создания собственной структуры. Но это не рекомендуется!

#########Рекомендации по теме: ######### Причины и решения невозможности загрузки файлов css и js в php ci framework####### # ####Видео: 27 классических практических видеоуроков по интерфейсной JS-разработке############Видео: видеоурок по расширенному дизайну инфраструктуры JavaScript без онлайн-видеоуроков####### ### #####

The above is the detailed content of 2018 js review: The fundamental reasons for the existence of the framework are these. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles