[Path to front-end templates] I. The reconstructed brother said: I don't want to read your code! Give me the HTML!

Source: Internet
Author: User
Preface

With the development of the front-end field and the need for a social division of labor, after the front-end siege, another important job is born-restructuring the siege! One of the major features of the so-called rebuilding and siege attack is that they are proficient in writing CSS configuration files... Front-end siege wet and restructuring siege wet is a good friend, you write logic, I write style.

Well, this article does not introduce the reconstruction of the occupation of city siege, but uses a simple scenario to say:

1. Before using the front-end template, are we swollen and dynamically creating nodes?

2. Why should I use a front-end template?

A simple scenario

Which of the following images looks familiar? Yes, it's from the Mac QQ friends list. As a front-end attacker, I believe that the first response of many shoes is: what HTML structure should be used to identify it? How to Write a style?

Well, let's assume that we can use the DOM structure below to identify this "friend" without considering its rationality. At the same time, we can ignore the style part in a gorgeous way.

 <  Div  >      <  IMG  SRC  = "Http://www.example.com/img/bg.png"   />     <  H3  > Card Test number </  H3  >      <  Div  > Hello everyone, I'm a personalized signature. </  Div  >  </  Div  > 

As we all know, our QQ friends list is not fixed, so we have to"Dynamic Creation". Do we usually get swollen?

The old wet said: The createelement is king.

The old wet once taught us not to create nodes through innerhtml, because it will makeCodeIt becomes messy. I also got the title of a good young pioneer, and of course I had to listen to the old wet talk, so I wrote the following code:

 VaR Card = Document. createelement ('div' );  VaR Avatar = Document. createelement ('img '); //  Avatar Avatar. src = 'HTTP: // www.example.com/img/header.png' ; Card. appendchild (Avatar );  VaR Nick = Document. createelement ('h3 '); //  Nickname  VaR Nicktxt = Document. createtextnode ('Card test No'); Nick. appendchild (nicktxt); card. appendchild (Nick );  VaR Signature = Document. createelement ('div '); //  Personalized Signature  VaR Signaturetxt = Document. createtextnode ('Hello, I'm a personalized signature' ); Signature. appendchild (signaturetxt); card. appendchild (signature ); 
Createelement Problems

After knocking on the above code, I smiled with satisfaction:Old wet you pitfall me where! Just a few broken nodes let me tap so much code?

Okay, then I realized that I was wet by mistake. He asked me to create nodes in the createelement method, but I didn't say that I would be beaten. One of the sources of human progress is laziness. the great value of computer existence is to liberate productivity. Why don't we change our mindset and let Code help us generate code? Code Generation Code? It's not difficult to hear about it. Please refer[Road to front-end templates] 2. Spam, let Code help us write code is king

Well, even if we did "Let the code write code for us" and look at what we 've been hitting, have you found any problems?

Talking to myself is the most discussed problem:The Dom structure is not intuitive,You have no idea that the node structure you have created is like a magic horse !!

For someone else to take over your code, the first thing is to run the above Code again, and then the endurance child opens the console to flip the DOM structure again, so that you can see what the above Code has made. Okay, let me change it...

Summary:Manual effort, not intuitive

Innerhtml we used together in those years

Major General Mao said: innerhtml is a good property! Let's see if we are doing innerhtml, will we do it?

 
VaRCard = Document. createelement ('div'); Card. innerhtml= '' + ' 

Wow! You only need a few lines of code to get it done. Ma no longer needs to worry about working overtime! Write code, so easy!

Everything seems wonderful, but it's slow! What if we want to create a batch of nodes now? I have written all the information above and it is not common!

It's easy to extract the dynamically changed fields, as shown in the following code.

 
FunctionCreatecard (avatarurl, Nick, signature ){VaRCard = Document. createelement ('div'); Card. innerhtml= '' + ';ReturnCard;} createcard ('Http: // www.example.com/img/bg.png', 'Card test No. ', 'Hello everyone, I am a personalized signature ');
Innerhtml Problems

Very good. The string is added together with a bunch of quotation marks. It seems that something is wrong. The above scenario is very simple. The dynamic content is just three pictures, nicknames, and personalized signatures, but the real world is much more complicated than we expected. If we want to extend the displayed friend information to the following, including the online status, membership, and mobile phone number, then the above Code may become like this (only for YY)

 Function  Createcard (avatarurl, Nick, signature, onlinestate, isvip, ismobileonline ){  VaR Onlinetxt ='' ;  Switch  (Onlinestate ){  Case 0 : Onlinetxt = 'Line' ;  Break  ; Case 1 : Onlinetxt = 'Offline' ;  Break  ;  Case 0 : Onlinetxt = 'Busy' ;  Break  ;  Default  :  Case 0 : Onlinetxt = 'Line';  Break  ;}  VaR Card = Document. createelement ('div '); //  Brothers with excellent performance can see the following code table hitting me with bricks  Card. innerhtml = '' + //  Avatar '<H3>' + Nick + ' //  Nickname '<Div>' + onlinetxt + '</div>' + // Online status '<Div>' + (isvip? 'Member ': 'non-member') + '</div> '; //  Member or not      If  (Ismobileonline) {card. innerhtml + = '<Div>' + (ismobileonline? 'Mobile phone online': '') + '</div> '; //  Online mobile phone?  } Card. innerhtml + = '<Div>' + signature + '</div> '; //  Personalized Signature      Return  Card ;} 

Obviously, the code is getting a little messy. With the ID, class, and other attributes added, I believe it will be spectacular...

Disadvantages: Poor maintainability(The solution will be mentioned later)

The reconstructed kids shoes said: I don't want to read your code!

The above briefly compares the createelement and innerhtml methods for creating nodes. It is not difficult to see the author's tendency-innerhtml.

With the development of the front-end field and the need for a social division of labor, after the front-end siege, another important job is born-restructuring the siege! One of the major features of the so-called rebuilding and siege attack is that they are proficient in writing CSS configuration files...

Front-end siege wet and restructuring siege wet is a good friend, you write logic, I write style.

> The reconstructed brother said: hand in your HTML!

So I gave the previous code to him.

 
VaRCard = Document. createelement ('div'); Card. innerhtml= '' + ';ReturnCard;

> Reconstruction brother :... Who should look at your code? I should look at the HTML structure !!

> Me :... There is a piece ~~ Do you want to call createcard?

> The reconstructed brother is furious: Would you like to try the Millennium kill ?!!

> Me :??!! Wipe, don't ~~ You cool and so on ~~~

As a result, I gave it the following, or the beginning of the HTML, but replaced all the dynamically changed content in the form of $ XX.

 <  Div  ID  = "My_tmpl"  >      <  Div  >         <  IMG SRC  =  "  $ {Avatar}  "   /  >          <  H3  >  $ {Nick} <  /  H3>          <  Div  >  $ {Signature}  <  /  Div>      <  / Div>  </  Div  > 

When the reconstructed kids shoes get what they want, if they are satisfied, they will go back and write his CSS. What about us? It is also very simple. The original spelling string, now the regular expression variable, is as follows:

VaRData ={Avatar:'Http: // www.example.com/img/bg.png', Nick:'Card test No', Signature:'Hello everyone, I'm a personalized signature'};VaRHtml = Document. getelementbyid ('My _ tmpl'). Innerhtml; html= Html. Replace (/\\ \ {(. + ?) \}/G,Function(ALL, $1) {// Replace $ {XX} with data [xx]ReturnData [$1] ;});

Here we have vaguely seen the front-end template. The first step in the separation of structure, style and logic has been achieved. The reconstructed kids shoes write CSS styles according to the agreed HTML template, the front-end kids shoes are responsible for filling in the template content, updating content, binding events, processing user interactions, etc. The benefits of doing so are obvious:

1. structure, performance, and logic separation to facilitate restructuring and division of labor between front-end children's shoes

2. better maintainability, and no longer need to be confused by a bunch of createelements or broken strings

It turned out to be this: the nature of the front-end template engine

Looking at the previous $ {Avatar} and $ {Nick}, many children's shoes should have similar feelings. Yes, the replacement identifier here, which is the same as the variable replacement identifier of jquery tmpl, can refer to the https://github.com/BorisMoore/jquery-tmpl

The essence of the front-end template engine is to replace variables.

Do you think this is the front-end template engine! If you feel this way, then:

1. How mysterious do you think the front-end template engine is? It was originally wrapped around and ended up with variable replacement.

2. What too young, to simple, sometimes, too naive. Front-end template engine does is not only to replace variables, but also to process logical judgment, loops, template nesting,Pre-renderingPre-processing and so on, there is a variable replacement, it is really embarrassing to say that it is a front-end template engine ..

Okay, there is still a problem to solve. CTRL + F find the following code.

If(Ismobileonline) {card. innerhtml+ = '<Div>' + (ismobileonline? 'Mobile phone online': '') + '</div> ';//Online mobile phone?}

This is actually what we need to do for logical judgment. If we use jquery tmpl, we can write it like this.

 
<Div>{If ismobileonline} mobile phone online {/if }}</Div>

Jquery tmpl usage, here do not intend to expand, can refer to: http://www.cnblogs.com/think8848/archive/2011/07/17/2108570.html

For more information about the source code of jquery tmpl, seeArticle~~

Post

This article uses a scenario to explain why we need to use a front-end template. As for the design of the front-end template, we will not mention it for the time being.

where to write the code? The logic is slightly messy. Sorry ~ The code word is not easy. Please click here to recommend it ~~

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.