Front-End programmer must know: the core of single page application

Source: Internet
Author: User

Over the years, the framework for single page applications has been overwhelming and new concepts have emerged. From the past JQuery Mobie, backbone to today's angular 2, react, Vue 2, they have a lot in common except for the version number.

When I first started writing Commercial Code, I used jQuery. Using jquery to implement features is easy, find a corresponding JQuery plug-in, and then write the appropriate function. This is also true for single page applications, looking for a complementary plug-in that can be used, such as JQuery Mobile.

Although today's view, JQuery Mobile is not suitable for most of today's scenarios. The main reason for this is that the user's understanding of mobile WEB applications is different today. They feel that mobile Web apps are customized for mobile devices, the UI for mobile devices, faster load speeds, and so on. Today, most mobile Web apps are almost single page apps.

In the past, even if we wanted to create a single page application, there might not be a suitable solution. Today, there are many options available (PS: See the fourth chapter: Learning the front end only need three months "frame"). Everyone in different types of projects, there will be different scenarios, no framework to solve all the problems for the job, I would prefer a complete solution. For the programming experience, I like to create some wheels in a little bit.

The more frames we use, the more time we choose to spend . The single page application has some of the same elements, the understanding of these basic elements, we can quickly adapt to other frameworks. the evolution of single page application

When I touch a single page application, it looks like it's putting everything on one page . Just write all the required templates in one HTML and data-role on different pages to show that it's a page (based on JQuery Mobile)--each defined page is similar to today's mobile application pattern, with header, content, footer three-piece sets. Then use the ID to define the appropriate route.

<div data-role= "page" id= "foo" > ...
</div>

So we're going to return all the pages in one HTML. Then, just write the appropriate ID in the href at the entrance.

<a href= "#foo" > Jump to Foo</a>

When we click on the corresponding link, we will switch to the corresponding ID in HTML. This simple single page application is basically an offline application, only suitable for simple scenes, but it has the basic characteristics of single page application. and complex applications, you need to get data from the server. However, the early effects of mobile browser performance were limited to getting the appropriate HTML from the server and replacing the current page.

In this application, we can see the basic elements of a single page application: page routing , in some way, such as URL hash to indicate the current page, and have a jump from one page to another page of the portal.

As the performance of mobile devices is getting better, developers are starting to render pages in browsers: using jquery to do page interaction using jquery Ajax to get data from the server using backbone for routing and Model using mustache as the template engine to render the page Use Require.js to manage different templates use Localstorage to store user data

By combining this series of tools, we can finally implement a complex single page application. And these are the basic elements of the single page application that we see today. We can see the shadow of these basic elements in angular application, react application, vue.js application, such as: Vue Router, React Router, angular 2 routermodule are responsible for routing (page jump and module relationship). In Vue and react, they are all implemented by auxiliary modules. Because react is just a layer of UI layer, Vue.js is also the framework for building the user interface. Routing: page jump vs. module relationships

It's a long story to talk about routing. When we enter the Web site in the browser, we have started a variety of routes of the journey. The browser will check that there is no corresponding domain name cache, no words will go to the DNS server to seek, and finally return the corresponding server IP address. Then, the Web site we are requesting will be processed by the corresponding IP HTTP server, which will be processed by the corresponding application container according to the request. Subsequently, our application will give the request to the corresponding function according to the path of the user's request. Finally, return the corresponding HTML and resource culture

When we do background apps, we only need to be concerned with the last step of the process. That is, the corresponding route is assigned to the corresponding function to handle. This, in the different backstage frame the manifestation is similar.

As in the Python language, the Web development framework Django URLConf, using regular expressions to table positive

URL (r ' ^articles/2003/$ ', views.special_case_2003),

In Laravel, it is presented in the form of parameters

Route::get (' posts/{post}/comments/{comment} ', function ($postId, $commentId) {
    //
});

Although there are some differences in the form of expression, but overall is also similar. And for front-end applications, the same is true, the corresponding URL logic to the corresponding function to deal with .

React Router uses a similar form to handle routing, as shown in the following code:

<route path= "blog" component={bloglist}/>
 <route path= "Blog/:id" Component={blogdetail}/>

When the page jumps to the blog, the control will be addressed to the Bloglist component.

When the page jumps to BLOG/FASFASF-ASDFSAFD, the two routes will be matched to the Blogdetail component for processing. The ID value in the route is also processed as a parameter Blogdetail component.

Similar, and the form of angular 2 is:

{path: ' blog ',      component:bloglistcomponent},
{path: ' Blog/:id ',      component:blogdetailcomponent},

Similarly, the blogdetailcomponent here is a component, and the ID value in path is passed to the Blogdetailcomponent component.

From the above, although the presentation is different, the behavior is consistent: Use the rule engine to handle the relationship between routes and functions. In a slightly different way, the backend routing is completely controlled by the server, and the front-end request changes its state locally.

And at the same time in different front-end frameworks, they have some differences in behavior. It depends on whether we need background rendering, that is, when the current page is refreshed. Use the form of hash (#) or hash Bang (#!). The Parameter form at the beginning of the #, such as Ued.party/#/blog. When we visit BLOG/12, the URL becomes UED.PARTY/#/BLOG/12 using the new HTML 5 history API. The URL that the user sees is the same as the normal URL. When a user clicks on a link to enter a new page, the history pushstate is used to fill in the new address. When we visit BLOG/12, the URL becomes UED.PARTY/BLOG/12. When the user refreshes the page, request the content from the server with a new URL.

Fortunately, most of the most recent Router components will determine whether to support the history API, and then decide which option to use first. Data: Acquisition and authentication

When implementing a route, only the corresponding control is handed over to the controller (or component) for processing. As a single page application of the controller, when the implementation of the corresponding controller, you can according to the corresponding BLOG/12 to get the ID that the user wants is 12. At this point, the controller will need to set a loading state on the page, and then send a request to the backend server.

For data acquisition, we can get the data by encapsulating the XMLHttpRequest Ajax, or we can get the data through the new, Promise fetch APIs, and so on. The Fetch API is not much different from the Ajax that has been Promise encapsulated, and we are still writing similar forms:

Fetch (URL). Then (response => Response.json ())
  . Then (data => console.log (data).
  catch (E => Console.log ("Oops, Error", E))

For complex data interactions, we can solve similar problems through RXJS. In the whole process, the more complicated place is the processing of data authentication and model.

The trouble with the model is that it turns into the desired form. The value returned in the background is variable, it may not return, it may be null, or it is not the same as the value we want to display-want to show is 54%, the back of the table returns 0.54. At the same time, we may also need to do a simple calculation of the value, showing a range, interval, or two different shows.

We also need to store these values locally, or in memory, when necessary. When we re-enter this page, we read the values again.

Once we talk about the data, it is inevitable that we need to be concerned about the security factors. For ordinary WEB applications, there are two things we can do to keep the data secure: HTTPS: Guarantees that the data is encrypted during transmission. Authentication: Make sure that the specified user can access only the specified data.

At present, the popular front-end authentication way is Token form, can be the ordinary custom Token, also can be the JSON Web Token. The form of Token is obtained through BASIC authentication--The user name and password entered by the user are sent to the server through BASE64 encryption. The server decrypts and verifies that it is a normal username and password, and returns a Token with a period of time to the front end.

Then, when the user gets the data that needs permission, the Header is required to identify whether the Token is limited, and then return the corresponding data. If the Token has expired, return 401 or similar flags, and the client clears the Token at this time and lets the user log back in. data display: Template engine

Now that we've got the data, the next thing we need to do is show that data. Compared to other content, the display of data is a simple thing: to show, hide some data in the template to traverse the data display in the template to execute methods to get the appropriate value, can be a function, or a filter. Dynamically acquire styles based on different values

There are some differences in different frameworks. And the modern front-end framework can support one-way or two-way data binding. When the corresponding data changes, it can be automatically displayed on the UI.

Finally, on the UI that needs to be processed, bind the corresponding event to handle it.

Just when the data is displayed, another problem is involved, that is, the component. For some elements that need to be reused, we will extract them into a common component so that we can reuse them.

<my-sizer [(size)]= "fontsizepx" ></my-sizer>

And in these components, the corresponding parameter changes, i.e. state change, are also involved. Interaction: Event and State management

After completing the step-by-step rendering, what we need to do is to interact. Interaction is divided into two parts: User interaction, interaction between components--shared state. Component Interaction: state Management

When users jump from page A to page B, to understand the relationship between the coupling components, we do not use the parameters of the component to pass in the value. Instead, the values are stored in memory, and these values are paged out at the appropriate time. When we deal with whether the user is logged in, we need a islogined method to obtain the user's status, we need a Setlogin method when the user logs in, we also need to update the user's login status when the user log out.

Before Redux, I would write a service to manage the status of the application. In this module, write a setter, getter method to store the value of the state, and write a few to manipulate the value according to the business function. However, when using service, it is difficult to track changes in state, and additional code is needed to deal with it in particular.

Sometimes you will be lazy and write a global variable directly. This is the time to maintain code is a nightmare, you need to search for the corresponding variables globally. It's easier to find where the call is if you're calling a particular Service. user interaction: Events

In fact, for user interaction it is only the value that changes the state, that is, the state is manipulated.

For example, when the user clicks on the login, send data to the background, returned by this value in the background. The controller one by one modifies these states, and finally confirms that the user is logged in, concurrent with a broadcast that the user has logged on to, or modifies the global user value.

Excerpt from: My career is a front-end engineer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.