Build front-end architecture with modular thinking and templating engine (Require+underscore)

Source: Internet
Author: User

    • Require.js

Description: A very compact JavaScript module loading framework , one of the best implementations of the AMD specification. The latest version of Requirejs is only 14K compressed and is very lightweight.

Official website: http://www.requirejs.cn/(PS: If have not touched, just start to see is a blind, suggest to see the Novice tutorial)

Beginner's Tutorial: http://www.runoob.com/w3cnote/requirejs-tutorial-1.html

Advantages: A complex set of requirements, such as teamwork, module reuse, unit testing, etc.

    • Underscore.js

Introduction: JavaScript Utility library, providing a full set of functional programming functions

Api:http://www.bootcss.com/p/underscore/

Use: Here only underscore as a template engine to use, using the _.template syntax (basic functions on demand, anyway production mode only 5K)

    • Code Hosting Address: Https://github.com/GerryIsWarrior/require-underscore (can download source)

Because change work took over a bank project, just beginning to start, and then a little look at the use of things, the project's front-end structure of all the key out, made a small demo, and then learn from their own, and now share out everyone learn, oneself also do a memo. Don't say much nonsense, start to pull the light.

    1. The first step is to build the background directory schema.

In require's official documentation, we recommend this layout directory:

For the official layout scheme is only the official proposal of a single pure require layout, but our project can not only use require, and then I refer to the Bank project directory structure, and then think about the convenience and readability, feel this package is still possible, directly

Simply explain:

    • App files: Store a purely static page layout used in your project
    • Resource file: Store all the resources you can request
    • App files: Css,js and TPL (template) for sub-modules
    • Common file: Store all the common things
    • Config file: The configuration file that holds the Require
    • TPL file: A common template (such as the head of a Web page, and a foot or other almost unchanged template)
    • Utils File: Public tool template exists
    • CSS files: storing global CSS files
    • Images files: Storing picture files
    • LIB file: A class library for all third-party management

Well, the directory is like this, such a directory to think about a bit or very reasonable, otherwise there will not be so many bank projects to follow this directory structure.

2. Import require, configure the Require configuration file, and then use require to manage JS files uniformly

The index.html code is as follows:

<! DOCTYPE html>data-main= " Resources/common/config/requireconfig "src=" Resources/lib/require2.2.0.js "></script><script>    require (['.. /.. /app/index/js/index '], function (login) {        new login ();    }); </script>

Throughout the page, we're just building a page layout (3 div) and then plug the module code we're going to show in these layouts. This is the HTML content that we see, for all JS, only need to refer to a require JS file, and then use Data-main in the file to specify a configuration file, in require use Data-main specified this file, The equivalent of telling require the starting search location for this directory.

Now let's look at the configuration of Requireconfig.js

Require.config ({    //Specify Base directory    BASEURL: "Resources",    //Configure basic information for various libraries    paths: {        ' underscore ': ' lib/ Underscore ',        ' jquery ': ' lib/jquery-1.12.1.min ',        ' class ': ' Lib/class ',        ' text ': ' Lib/text '   // Text is a module of require, when you load the configuration file, automatically introduced the project itself    },    //Configuration Output    shim: {        ' underscore ': {            exports: ' _ '        }    }});

In this configuration file, we configure the BaseURL, specify a root directory, and then configure path, which is all of our managed JS files, and then configure the shim output file. As for the basic concept is not very understand, you can check the API, here I will not be cumbersome to say

3. Create template file The JS file used by TPL and module

We create a directory of the index module in the app in resource, and then build the TPL template and JS file we need here.

PS:TPL is just a suffix, in essence, TXT file, you can create a TXT file, but because of the habit, and give a look to understand that the end of the TPL is the template

The Index.js code is as follows:

Define (function (require) {    require ("jquery");  Use require to load the required JS, like node require loading module, and Webpack installed modules, and then load this module    require ("underscore");    var class = require ("class");  Class is an object class that can be used to create an object and then throw out    var login = class.extend ({        //constructor method, this method is mandatory, as long as you create this class        initialize: function () {            this.render ();        },        //other method        Render:function () {            //Initialize template           var header_text = Require (' Text!app/index/tpl/headcontent.tpl ');            var header_html = _.template (Header_text) ({person: {name: "Gerry"}});            $ ("#header"). HTML (header_html);        }    });    return login;});

This require asynchronous load this JS, the callback can throw this object, and then new this object, you can call this JS module and some of the settings, that is, the index.html code in bold red JS.

Headcontent.tpl Template Code

<div style= "color:red;" >    Hello: <%=person.name%> This is the header information, showing the angle brackets of the head module is the parameters of the    underscore template engine </div>

In this TPL, the information of the head is shown, which is only tested, too simple, and then a parameter is written.

4. Use underscore to load the TPL and plug the required data into the page

We processed this data in the index.js.

  var header_text = require (' TEXT!APP/INDEX/TPL/HEADCONTENT.TPL '); This sentence uses the Require text's sub-function to search for and read this template content

  var header_html = _.template (Header_text) ({person: {name: "Gerry"}}); This sentence uses the underscore template method to plug the parameters into the templates and render them as HTML tags

  $ ("#header"). HTML (header_html); This is, of course, loading the template into a static layout, and then it comes out.

The effect is as follows:

PostScript: The development trend of the front-end is very fierce, perhaps the technology and framework update quickly, today with this tomorrow with this. Maybe one months is still in use require, next month will use Webpack, and next month will use node what what, but I feel the most basic is will not change, original aim, JavaScript Foundation to learn. Second, there is no so-called rapid development of the framework is the best, only according to the size of the project you asked to do, what the need to choose some framework, suitable for the best, do not blindly go after a lot of the latest best of what. Well, it's already night, it's time to rest, I have to go to work tomorrow, good night, guys ...

Build front-end architecture with modular thinking and templating engine (Require+underscore)

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.