JS Modular Programming
There are many JavaScript loaders in the world, such as sea.js, require.js, Yui loader, Labjs... The use of the loader is a large number of projects, personal feeling if it is small projects can not, I used seajs and Requirejs, in the project used Requirejs, REQUIREJS is compliant with AMD, the full name is (asynchronous module Definition) is the asynchronous module loading mechanism, SEAJS is a CMD-compliant loader.
Amd__ and __cmd
The AMD specification is dependent on the predecessor, the CMD specification is dependent upon the post, and the AMD Spec Loader will put all of the JS dependencies in front of the execution . cmd is lazy loading , if JS need this module to load, otherwise do not load, resulting in the problem is in line with the AMD Specification loader (REQUIREJS), may load the first time will be relatively long, because he put all the dependent JS all-in-one download down;
Common sense,jquery is to support the AMD specification, does not support the CMD specification, that is, if the introduction of SEAJS, want to use JQuery, to configure with alias , or directly Http://cdn.bootcss.com/jquery/2.1.4/jquery.js directly into the page;
Run the following code
This is the last line of the jquery source code, jquery to 1.7 to support modularity;//Register as a named AMD module, since jquery can be concatenated with other//file s, may use define, but not via a proper concatenation script that//understands anonymous AMD modules. A named AMD is safest and the robust//to register. Lowercase jquery is used because AMD module names are//derived from file names, and jquery are normally delivered in a low ercase//file name. Do this after creating the global so if a AMD module wants//to call Noconflict to hide this version of JQuery, it w Ill work.//Note that for maximum portability, libraries that is not jQuery should//declare themselves as anonymous Modu Les, and avoid setting a global if an//AMD loader is present. JQuery is a special case. For more information, see//https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anonif ( typeof define = = = "function" && define.amd) {define ("jquery", [], function () {return jquery; });};
How to use
For example, we can define a module like this:
Run the following code
The path where the file is located is: Http://localhost:63342/module/script/dir2/1.jsdefine (function () { return]!!! ";});
You can also define a module like this:
Run the following code
The path of this file is Http://localhost:63342/module/main.js, and there is a dependency, the loader will automatically load this dependency, when the dependency loading is completed, will be the dependency (that is, script/dir2/1.js) The return value of the execution is passed in as a parameter to the function, require (["script/dir2/1.js"], function (Module1) { console.log (module1);});
Will actually print out "!!!" "
In general, a module can only write a define function, the Define function of the main parameters are two ways:
1: normal can be a function;
2: can be an array type dependent list, and a function;
If a module writes more than one define will cause the module to fail, the first defined module is covered by the later defined module (of course, we do not play that way);
A module can write multiple require, we can directly understand the require as an anonymous define module, a define module can have more than require, and the require of the module will be cached, this cache variable is generally in the closure, And the names are mostly called modules or something ..... ;
Our modular development through the loader development to comply with a specification , the specification of a module for a JS, then we can create a few directories for Conroller,view, model, but also for the later better maintenance and decoupling :
Implement a loader of your own
How to use:
Run the following code
This module relies on the four modules, the loader will load the four modules separately; define (["Dependent 0", "Dependent 1", "Dependent 2", "Dependent 3"], function (dependency 0, Dependency 1, Dependency 2, dependency 3) {});//Returns an empty object define ( function () { return {};}); /direct require as a define to use it; require (["Dependent 0", "Dependent 1", "Dependent 2", "Dependent 3"], function (dependency 0, Dependency 1, Dependency 2, dependency 3) { //execution dependency 0; Dependency 0 (Dependent 1, Dependency 2, dependency 3); /The difference between this loader define function and the Require function is, define we can pass a name as the first parameter, this parameter is the module's name????, OK, whatever it is ...
The following is the structure of the loader , because the amount of code is very small, so each function is necessary, in order not to affect the global, put the code inside the anonymous self-executing function:
Run the following code
(function () {defines a local difine; var define; I secretly added a global variable, good debugging AH; Window.modules = {}; Obtaining an absolute path through a name such as "Xx.js" will become "http://www.mm.com/" + baseUrl + "xx.html"; var getUrl = function (src) {}; Dynamic loading JS module; var loadscript = function (src) {}; Get the root path method, in general we can configure this path through Config.baseurl; var getbasepath = function () {}; Gets the script tag Dom node that is currently being loaded; var getcurrentnode = function () {}; Gets the absolute src address of the current script tag; var getcurrentpath = function () {}; Loading define or require dependencies, encapsulating the Loadscript method; var loaddpt = function (module) {}; This is the main module, complete the load dependency, detection dependency and other important logical var Checkdps = function () {}; Defines the Define method define = function (Deps, FN, name) {}; Window.define = define; Require is the encapsulation of the Define method, is to pass a parameter only; Window.require = function () {///If it is require, then the name of the module is a non-repeating name, avoid and define duplicate names; Window.define.apply ([], Array.prototype.slice.call (arguments). Concat ("module|" +settimeout (function () {},0))); };});
Loader source code implementation (compatible, chrome, FF, ie6 ==>> ieone), IE11 no readystate attribute, no currentscript attribute, Pit Daddy, Unable to get the currently executing JS path, so use hack;
Run the following code
<! DOCTYPE html>A loader from the big side of the leaf, this loader is a bit like the lingering object in jquery ($. Deferred) The implementation of the method when ($.when);
Run the following code
View CodeAn exampleWrite a small example of MVC , the code is simple, the master ignores, the directory structure is as follows:
We put all the events into the controller/maincontroller.js,
Run the following code
Define (["Model/data", "View/view0"],function (data, view) { var init = function () { var body = document.getElementsByTagName ("Body") [0]; var abtn = document.getelementsbytagname ("button"); for (var i=0; i< abtn.length; i++) { Abtn[i].onclick = (function (i) { return function () { body.appendchild (View.getview (Data[i]); }; }) (i); }; }; return { init:init };});
Put all the data into the model/data.js;
Run the following code
Define (function () {return [{name: ' Qihao '}, {name: ' Nono '}, {name : ' hehe '}, {name: ' Gege ' } ];})
The view JS is put in The view directory,View0.js is mainly responsible for generating HTML strings or DOM nodes;
Run the following code
Define (function () { return { getview:function (data) { var frag = document.createdocumentfragment (); Frag.appendchild (document.createTextNode (Data.name + "")); return frag;}} );
The entrance is App.js, and he and load.html are in the same sibling directory:
Run the following code
Require (["Controller/maincontroller"],function (Controller) { controller.init ();});
Load.html This is the main interface:
Run the following code
<! DOCTYPE html>
Example of source code: Download
Next week began to review the jQuery1.8 version of the source code, and then next week to prepare to write some books, including JS design mode, JS Ninja, JS the door of the wonderful, Reactjs study.
Reference:
JS Magic Hall: Gets the absolute path of the current script file
JAVASRIPT Module Specification-AMD specification and CMD specification introduction
"Modular Programming" understanding requirejs-implementation of a simple module loader
NONO
Source: http://www.cnblogs.com/diligenceday/
qq:287101329
JS Modular Programming