Seajs_javascript Techniques of JavaScript modular development

Source: Internet
Author: User
Tags define function script tag

Objective

Seajs is a JavaScript module loading framework that follows the COMMONJS specification, and can realize the modular development and loading mechanism of JavaScript. Using SEAJS can improve the readability and clarity of JavaScript code, solve the problem of dependency confusion and code entanglement in JavaScript programming, and facilitate the writing and maintenance of code.

Seajs itself follows the kiss (Keep it simple,stupid) concept of development, followed by several versions of the update is noisy in this direction.

How to use Seajs

Download and install here do not repeat, do not understand the Please check the official website.

Basic development Principles
• Everything is modular: the concept of modules in Seajs is somewhat similar to 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 invoked by other modules.

• Each module should be defined in a separate JS file, that is, a corresponding module.

Definition and writing of modules

Module definition function define

The Define function is used in SEAJS to define a module. Define can receive three parameters:

/**
* 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 ...
}

The parameters that define can receive are module IDs, dependent module arrays, and factory functions.

• If there is only one argument, assign to factory

• If there are two parameters, the second assignment to factory, the first if the array is assigned to Deps, otherwise assigned to the ID

• If there are three parameters, assign the values separately

However, including the SEAJS official website example, where almost all define are used, only one factory function is passed in, similar to the following code:

Define (function (require,exports,module) {
  //code of the module

Personal advice is to follow the SEAJS official example and define the module with the define of a parameter. 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 Analysis of Factory function

The factory function is the main body and the key point of the module. Its three parameters are:

require: module load function, for documenting dependent modules
exports: An interface point that exposes a data or method to an external call when it is defined on it
module: Meta data for modules

These three parameters can optionally select whether to display the specified.

A module is an object that stores meta information for modules, as follows:
module.id: ID of module
module.dependencies: An array that stores the list of IDs for all modules that this module relies on.
Module.exports: Pointing to the same object as exports

Three modes of writing modules

The first is based on the exports pattern:

Define (function (require,exports,module) {
  var a=require (' a ');
  var b=require (' B '); Introducing Module
  var data1=1//Private Data
  var fun1=function () {//Private method return
    A.run (data1);
  }
  exports.data2=2; Public Data
  Exports.fun2=function () {return
    ' hello ';
  }
})

The above is a more "authentic" module definition pattern. In addition to talking about public data and methods attached to exports, you can also return an object representation module directly, as the following code has the same function as the preceding code:

Define (function (require) {
  var a=require (' a ');
  var b=require (' B '); Introducing Module
  var data1=1;
  var fun1=function () {return
    a.run (data1);
  }
  return{
    Data2:2,
    fun2:function () {return
      ' hello '
    }
}})

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

Define ({
  data2:2,
    fun2:function () {return
      ' hello ';
    }
  

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

Depending on the scenario, SEAJS provides three APIs for loading modules, respectively: Seajs.use,require and Require.async.

Seajs.use

Seajs.use is mainly used for loading portal modules. The entry module is equivalent to the main function of C, which is also the root of the entire module dependency tree. Seajs.use
The following are the uses:

The first 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 use of multiple modules and Kissy in the module loading method is similar, no loss is a person wrote Ah!

The general Seajs.use is only used 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" property to the script tag that introduces Seajs, for example:

<! DOCTYPE html>
 
 

Require is the SEAJS main module loading method, which is typically loaded with require when other modules are needed in a module:

var m=require ('. a '); 
Require.async

Above said Seajs will be open in the HTML page through static analysis of a one-time record of all the required JS files, if you want a JS file in time to load, you can use Require.async.

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.

Global configuration for Seajs

SEAJS provides a SEAJ.CONFIGD way to set up a global configuration and receive a configuration object that represents a global configuration, as follows:

Seajs.config ({
base: ' Path ',
alias:{
  ' app ': ' path/app/'
},
charset: ' Utf-8 ',
timeout:20000,
debug:false
})

which

base represents the base address path
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 the download file, in milliseconds.

How to use the SEAJS with the existing JS library

To use an existing JS library with SEAJS, you simply encapsulate an existing library based on SEAJS's module definition rules. For example, here's how to encapsulate jquery:

Define (function () {/
  *
  Here is the jquery source code
  * *
  

A complete example:

Above said so many, the knowledge point is more dispersed, therefore finally I intend to use a complete seajs example to put these knowledge points together, facilitates the friend to generalize the review. This example contains the following files:
index.html main Face

Sea.js
Jquery.js
init.js init module, Portal module, dependent on data, jquery, style three modules, and home page loading
data.js Data module, pure JSON module
style.css CSS style sheet

HTML:
<! DOCTYPE html>
<! DOCTYPE html>
 
 

Please note:

1. Please speak the jquery.js source file contained in the SEAJS module loading code;

2. The CSS file can be loaded before the Sea.js < 2.3.0 version, and this feature is removed in the new version, and the load CSS feature will exist as a plugin for compatibility reasons.

How to use

• This plugin can be introduced after the sea.js tag is used
• Plug-in code can also be mixed into sea.js
• The difference between Seajs-style and Seajs-css is to enable sea.js to load a CSS file, just like the link tag
Seajs-style refers to providing a Seajs.importstyle method for loading a piece of CSS string

The above content is small to share the JavaScript modular development of the SEAJS, I hope to learn JavaScript modular development has helped, thank you all have been to cloud-Habitat community website support.

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.