SEAJS Basic Development Principles

Source: Internet
Author: User

SEAJS Basic Development Principles

Before discussing the specific use of SEAJS, first introduce the modular concept and development principles of SEAJS.
The basic principle of developing JavaScript with SEAJS is that everything is a module. When SEAJS is introduced, the JavaScript code is written into one module after another, and the concept of modules in Seajs is somewhat similar to those in object-oriented classes--modules can have data and methods, data and methods can be defined as public or private, and public data and methods can be called by other modules.
In addition, each module should be defined in a separate JS file, that is, a corresponding module.
The following describes the authoring and invocation of modules.

Definition and writing of modules

Module-defined function define
Use the "define" function in Seajs to define a module. Because Seajs's documentation does not have a complete reference to define, I read the SEAJS source code and found that define can receive three parameters:

Copy CodeThe code is as follows:/**
* Defines a module.
* @param {string=} ID of 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 is I extracted from the SEAJS source code, define can receive the parameters are module ID, dependent on the module array and factory function. I read the source code and found that define for the number of different parameters of the parsing rules are as follows:
If there is only one argument, assign the value to factory.
If there are two parameters, the second is assigned to factory, and the first one is assigned to Deps if it is an array, otherwise it is assigned to the ID.
If there are three parameters, the values are assigned to Id,deps and factory respectively.
However, the official example, including SEAJS, will only pass a factory function in almost all places where define is used, similar to the following code:

Copy CodeThe code is as follows:
Define (function (Require, exports, module) {
Code of the module ...
});

Personal recommendations Follow the standard of the SEAJS official example, defining the module with a define of a parameter. So what will the ID and deps do with it?
ID is the identity string of a module, and when define has only one parameter, the ID is assigned by default to the absolute path of this JS file. If the module is defined using define in the A.js file under example.com, the ID of this module is assigned to Http://example.com/a.js, and there is no specific recommendation not to pass in the ID. Deps generally do not need to pass in, the module needs to be loaded with require.

Factory Analysis of Factory function

The factory function is the main body and focus of the module. When passing only one parameter to define (recommended notation), this parameter is the factory function, at which point the three parameters of the factory function are:
The 1.require--module load function is used to record dependent modules.
A 2.exports--interface point that exposes data or methods to external calls when they are defined on them.
The metadata for the 3.module--module.
These three parameters can be selected as needed to show whether or not a specified is required.
Let's talk about module. The module is an object that stores the meta information of the 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 to define the module is based on the exports mode:

Copy CodeThe code is as follows:
Define (function (Require, exports, module) {
var a = require (' a '); Introduction of a module
var B = require (' B '); Introducing the 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 model that is more "authentic" than the module definition. In addition to attaching common data and methods to exports, you can also return an object representation module directly, as the following code functions the same as the code above:

Copy CodeThe code is as follows: Define (function (require) {
var a = require (' a '); Introduction of a module
var B = require (' B '); Introducing the B module

var data1 = 1; Private data

var func1 = function () {//Private method
Return A.run (DATA1);
}

return {
Data2:2,
Func2:function () {
return ' Hello ';
}
};
});

If the module definition has no other code and returns only one object, you can also have the following simplified notation:

Copy CodeThe code is as follows: Define ({
Data:1,
Func:function () {
return ' Hello ';
}
});


The third approach is appropriate for modules that define pure JSON data.

Loading and referencing of modules

The addressing algorithm of the module
As mentioned above, a module corresponding to a JS file, and loading the module is generally provided with a string parameter to tell the loading function needs the module, so there is a set of string identification to the actual module is located in the file path of the parsing algorithm. SEAJS supports the following identification:
Absolute address-gives the absolute path to the JS file.

Such as:

Copy CodeThe code is as follows: Require ("http://example/js/a");


The representative is loaded into the http://example/js/a.js.
Relative address--the relative address of the JS file where the function is loaded with the relative call to find the module.
For example, loading in http://example/js/b.js

Copy CodeThe code is as follows: Require ("./C");


is loaded into http://example/js/c.js.
Base Address--if the load string identity is neither an absolute path nor a "./", the method is addressed relative to the "base" in the SEAJS global configuration, which is discussed later.
Note that there is no need to pass the suffix ". js" when loading the module, SEAJS will automatically add ". js". However, the following three scenarios are not added:
When loading CSS, such as:

Copy CodeThe code is as follows: Require ("./module1-style.css");


The path contains "?" , such as:

Copy CodeThe code is as follows: Require (<a href= "Http://example/js/a.json?cb=func" >http://example/js/a.json?cb=func</a>);


When the path ends with "#", such as:

Copy CodeThe code is as follows: Require ("http://example/js/a.json#");


Depending on the scenario, SEAJS provides three load module APIs, Seajs.use,require and Require.async, respectively, as described below.

Seajs.use

The seajs.use is mainly used for loading the ingress module. The ingress module is the main function of the C program, and it is also the root of the entire module dependency tree. In the Tinyapp small example above, init is the entry module. Seajs.use usage is as follows:

Copy CodeThe 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 ();
});


The general Seajs.use is used only on the page to load the Ingress module, and SEAJS will parse all dependent modules along the Ingress module and load them. If the Ingress module has only one, you can also omit the seajs.use by adding the "Data-main" attribute to the script tag that introduces Sea.js, for example, the index.html of Tinyapp above can be changed to the following notation:

Copy CodeThe code is as follows:
<! DOCTYPE html>

<meta charset= "UTF-8" >
<title>TinyApp</title>

<body>
<p class= "Content" ></p>
<script src= "./sea.js" data-main= "./init" ></script>
</body>


This will make HTML more concise.

Require

Require is the main module loading method of Seajs, which is usually loaded with require when other modules need to be used in one module:

Copy CodeThe code is as follows: var m = require ('/path/to/module/file ');


Here is a brief introduction to the SEAJS automatic loading mechanism. As mentioned above, the use of SEAJS after the HTML as long as the inclusion of sea.js, then the other JS file is how to load it? Seajs will first download the Portal module, and then follow the portal module using regular expressions to match all the require in the code, and then according to the file path in the require to download the corresponding JS file, the downloaded JS file iteration to do similar operations. The entire process is similar to the traversal of the graph (because there may be cross-loop dependencies, so the entire dependent data structure is a graph rather than a tree).
Having understood the above, the following rules are well understood:
The path identifier passed to require must be a string literal and cannot be an expression, as the following method of using require is wrong:

Copy CodeThe code is as follows: Require (' module ' + ' 1 ');
Require (' Module '. toLowerCase ());


This will cause the SEAJS to fail to perform the correct regular match to download the corresponding JS file.

Require.async

As mentioned above Seajs will be in the HTML page open with static analysis of all the required JS files, if you want a JS file to download when used, you can use Require.async:

Copy CodeThe code is as follows: Require.async ('/path/to/module/file ', function (m) {
Code of Callback ...
});


This is only used in this module, the corresponding JS file will be downloaded, but also the implementation of the JavaScript code on-demand loading.

Global configuration of the SEAJS
SEAJS provides a Seajs.config method to set the global configuration and receive a configuration object that represents the global configuration. Here's how to use it:

Copy CodeThe code is as follows: Seajs.config ({
Base: ' path/to/jslib/',
Alias: {
' app ': ' path/to/app/'
},
CharSet: ' Utf-8 ',
timeout:20000,
Debug:false
});


Where base represents the base address path when the base address is addressed. For example, if base is set to http://example.com/js/3-party/, then:

Copy CodeThe code is as follows: var $ = require (' jquery ');


Will load into the http://example.com/js/3-party/jquery.js.
Alias can set abbreviations for longer common paths.
CharSet represents the CharSet property of the script tag when downloading JS.
Timeout indicates the maximum length of time, in milliseconds, to download a file.
Debug indicates whether it is working in debug mode.

Seajs how to work with existing JS libraries

To use an existing JS library, such as jquery and Seajs, you simply encapsulate an existing library based on the module definition rules of SEAJS. For example, here's how to encapsulate jquery:

Copy CodeThe code is as follows: Define (function () {

{{{{} jquery Legacy code starts
/*!
* JQuery JavaScript Library 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, the Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date:thu May 12 15:04:36 2011-0400
*/
//...
}}}jquery Legacy Code End

return $.noconflict ();
});


Packaged deployment of SEAJS projects

Seajs was originally integrated with a packaged deployment tool SPM, and later the author took the SPM out of Seajs to be a separate project in order to be a little more kiss. The core idea of SPM is to merge the code of all modules into the Ingress module, and because of the characteristics of SEAJS itself, HTML can easily switch between the development environment and the production environment because of its own features. However, due to the fact that SPM is not currently published, this article is not intended to be described in detail, and interested friends can refer to their GitHub Project homepage https://github.com/seajs/spm/.
In fact, because each project uses different JS merging and compression tools, the SPM may not be perfect for every project. Once you understand the SEAJS principle, you can write a merge package script that fits your project's characteristics completely.

SEAJS Basic Development Principles

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.