The Seajs Introductory Tutorial series uses SEAJS (ii)

Source: Internet
Author: User
Tags define definition html page json regular expression require script tag

  This article mainly introduces the introduction of the Seajs Tutorial series of Use Seajs, focusing on the use of SEAJS, the use of key methods and so on, the need for friends can refer to the following

Download and install   to use SEAJS in your project, all you need to do is download sea.js and put it in a location on your project. The SEAJS project is currently hosted on GitHub, and the home page is https://github.com/seajs/seajs/. You can download sea.js (compressed) or sea-debug.js (uncompressed) in the build directory of its git library. When the download is complete, put it in the appropriate position on the project, and then introduce it through the <script> tag in the page, and you can use SEAJS.   SEAJS Basic Development principles   in the discussion of the specific use of SEAJS, first introduced the seajs of the modular concept and development principles. The basic principle of using SEAJS to develop JavaScript is that everything is a module. When SEAJS is introduced, writing JavaScript code becomes the writing of one module after another, the concept of the module in Seajs is somewhat similar to the Object-oriented class--modules can have data and methods, data and methods can be defined as public or private, and public data and methods can be invoked by other modules. In addition, each module should be defined in a separate JS file, that is, a corresponding module. The following is an introduction to the writing and invocation of modules.   module definition and writing   module definition function define SEAJS uses the "define" function to define a module. Because the SEAJS document does not have a complete reference to define, I read the SEAJS source code and found that define can receive three parameters: the code is as follows:/** * defines a module. * @param {string=} ID the module ID. * @param {array.| string=} deps the module dependencies. * @param {function () | Object} factory the module factory function. */Fn.define = function (ID, deps, factory) {   //code of function ...}   above I extract from the SEAJS source code, define can receive the parameters respectively is the module ID, which relies on module arrays and factory functions. I read the source code and found that the define for the number of different parameters of the resolution rules are as follows: if there is only one argument, then assign to factory. If there are two parameters, the second assignment to factOry first if array is assigned to Deps, otherwise assigned to ID. If there are three parameters, the values are assigned to Id,deps and factory respectively. However, the official example of SEAJS, where almost all define are used, passes only one factory function, similar to the following code:     Code as follows: Define (function (Require, exports, module) {    //code of the module ...};   Personal advice to follow the SEAJS official example of the standard, with a parameter define definition module. So what do IDs and Deps do with it? ID is the identity string of a module, define only one parameter, the ID will be assigned by default to this JS file absolute path. If you use define to define a module in the A.js file under example.com, the ID of the module is assigned to Http://example.com/a.js and there is no special recommendation not to pass in the ID. Deps generally do not need to be passed in, the module needs to use the require load.   Factory function Factory parsing   Factory function is the main body and focus of the module. When passing only one parameter to define (recommended), this parameter is the factory function, at which point the three parameters of the factory function are: 1.require--module loading function, which is used to record the dependent module. 2.exports--an interface point that exposes the data or method to an external call. 3.module--the module's metadata. These three parameters can optionally select whether to display the specified. Let's say module. A module is an object that stores the meta information of modules, as follows: The ID of the 1.module.id--module. 2.module.dependencies--an array that stores the list of IDs for all modules that this module relies on. 3.module.exports--and exports point to the same object.   Three modes of writing modules   The first mode of defining modules is based on exports mode:     code is as follows: Define (function (Require, exports, module) {  &N Bsp var a = require (' a '); Introducing a module     var b = require (' B '); Introduction of B module       var data1 = 1; Private data       var func1 = function () {//Private method         return A.run (data1);     }       EXPORTS.DATA2 = 2; Public data       EXPORTS.FUNC2 = function () {//Public method         return ' hello ';     } });     Above is a more "authentic" module definition pattern. In addition to attaching public data and methods to exports, you can also directly return an object representation module, as the following code functions the same as the preceding code:     Code is as follows: Define (function (require) {    var a = require (' a '); Introducing a module     var b = require (' B '); Introduction of B module       var data1 = 1; Private data       var func1 = function () {//Private method         return A.run (data1);     }       Return {        Data2:2,         func2:function () {&NB Sp           return ' hello ';        }    ; });   If the module definition has no other code and returns only one object, you can also make the following simplification: The   code is as follows: Define ({  &nbsp Data:1     Func:function () {        return ' hello ';    }}); The third approach is appropriate for modules that define pure JSON data.   module's loading and quoting   module's addressing algorithm the above mentioned a module corresponding to a JS file, while loading the module is generally to provide a string parameter to the Load function required module, so you need a set from the string identification to the actual module in the file path of the resolution algorithm. SEAJS supports the following identification: Absolute address-give the absolute path of the JS file.   such as:     code as follows: Require ("http://example/js/a"); On behalf of loading http://example/js/a.js. Relative address--find the module with relative calls to the corresponding address of the JS file where the function is loaded. For example, load the copy code code in Http://example/js/b.js as follows: Require ("./C"); is loaded into the http://example/js/c.js. Base Address--if the load string identity is neither an absolute path nor a "./" Start, then the relative seajs of "base" in the global configuration is addressed in a later manner. Note that the above module is loaded without passing the suffix ". js", SEAJS will automatically add ". js". But the following three cases are not added: Load CSS, such as: Copy code: Require ("./module1-style.css"); The path contains the "?" , such as: Copy code code as follows: Require (<a href= "Http://example/js/a.json?cb=func" >http://example/js/a.json?cb=func</a >); The path ends with "#", such as: Copy code code as follows: Require ("http://example/js/a.json#"); Depending on the scenario, SEAJS provides three APIs for loading modules, Seajs.use,require and Require.async respectively, described below.   Seajs.use   Seajs.use is mainly used for loading portal modules. The entry module is equivalent to the main function of the C program and the root of the entire module dependency tree. Above the T.In the Inyapp small example, init is the Portal module. Seajs.use usage is as follows:   code is as follows://Single mode Seajs.use ('. a ');  //Callback mode Seajs.use ('. A ', function (a) {  A.run ();});  //multi-module mode seajs.use (['. a ', './b '], function (A, b) {  a.run ();   B.run ();});   General Seajs.use only use in the page loading portal module, SEAJS will follow the entry module to resolve all dependent modules and load them. If there is only one entry module, you can omit seajs.use by adding the "Data-main" attribute to the script tag that introduces Sea.js, for example, the index.html above Tinyapp can be changed to read as follows:   code is as follows: < ! DOCTYPE html> <html lang= "ZH-CN" > <head>     <meta charset= "UTF-8" >     <TITL e>tinyapp</title> <body>     <p class= "content" ></p>     </head> Lt;script src= "./sea.js" data-main= "/init" ></script> </body> </html>   This kind of writing will make HTML more concise.     require   require is SEAJS main module loading method, when other modules need to be used in a module is usually loaded with require:     code is as follows: var m = require ('/ Path/to/module/file '); Here is a brief introduction to SEAJS's automatic loading mechanism. As mentioned above, the use of Seajs HTML as long as the inclusion of sea.js can be, then the other JS file is how to load in it? Seajs will first download the Portal module and then follow the entry module using regular expression matchingCode all the require, and then according to the file path in require download the corresponding JS file, to download the JS file iteration for similar operations. The entire process resembles a graph traversal operation (because there may be a cross loop dependency so the entire dependent data structure is a graph rather than a tree). With this in mind, the following rules are well understood: The path identifier passed to require must be literal, not an expression, as the following method of using require is wrong: Copy code code as follows: Require (' module ' + ' 1 '); Require (' Module '. toLowerCase ()); This will cause seajs not to be able to properly match the corresponding JS files below.   Require.async   Above said Seajs will be open in the HTML page through static analysis of all the required JS file, if you want a JS file in use to download, you can use the Require.async:   The code is as follows: Require.async ('/path/to/module/file ', function (m) {   //code of Callback ...}); This only in the use of this module, the corresponding JS file will be downloaded, but also to achieve the JavaScript code on-demand loading.   SEAJS Global Configuration Seajs provides a Seajs.config method to set up a global configuration and receive a configuration object that represents a global configuration. The specific use of the following:     code as follows: Seajs.config ({    base: ' path/to/jslib/',     alias: {    &NBS P ' app ': ' path/to/app/'    },     charset: ' Utf-8 ',     timeout:20000,     DEBUG: False}); Where base is the path of the base address when addressing the base address. For example, base is set to http://example.com/js/3-party/, then: Copy code code as follows: var $ = require (' jquery '); will be loaded into the http://example.com/js/3-party/Jquery.js. The alias can set an abbreviation for a longer common path. CharSet represents the CharSet property of the script tag when downloading JS. Timeout indicates the maximum length of the download file, in milliseconds. Debug indicates whether the work is in debug mode.     SEAJS How to work with the existing JS library   to use the existing JS library, such as jquery and Seajs, you only need to encapsulate the existing library according to the SEAJS's module definition rules. For example, the following is the encapsulation method for JQuery:     Code is as follows: Define (function () { //{{{jquery original code/*!    * jQuery JavaScript L Ibrary v1.6.1  * http://jquery.com/ *  * Copyright, John resig  * Dual licensed under the MIT or GPL Version 2 licenses.  * http://jquery.org/license  *  * Includes sizzle.js  * http://sizzlejs.com/ * Copyright 2011 , the Dojo Foundation  * released under the MIT, BSD, and GPL Licenses.  *  * Date:thu may 15:04:36 2011-0400  *///...//}}}jquery original code end   return $.noconflict (); });     SEAJS Project Packaging deployment   SEAJS Originally integrated a packaged deployment tool SPM, and later the author to a more Kiss point, the SPM was removed Seajs and became a separate project. The core idea of SPM is to merge all the code of the module into the entrance module, and because of the characteristic of SEAJS itself, the HTML can easily switch between the development environment and the production environment. However, since the SPM has not released a formal version, so this article does not intend to introduce the details, interested friends can participate inLook at its GitHub project homepage https://github.com/seajs/spm/. In fact, because each project uses the JS merge and compression tools are different, so SPM may not be entirely suitable for each project. After understanding the principle of seajs, you can write a merge package script that conforms to your own project characteristics.  

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.