Opening! Design and Implementation of JavaScript AMD module, javascriptamd

Source: Internet
Author: User

Opening! Design and Implementation of JavaScript AMD module, javascriptamd

Open a trap and gradually learn and summarize JavaScript AMD specifications

First, let us put a simple implementation we have written, and then start to explain AMD from scratch, and how to implement an AMD by ourselves.

(Function (w, DOC) {var _ $ = w. $; var head = DOC. head | DOC. getElementsByTagName ('head') [0]; var html = DOC.doc umentElement; var W3C = DOC. dispatchEvent; var basePath = getCurrentScript (DOC); basePath = basePath. substring (0, basePath. lastIndexOf ('/') + 1); var hasOwn = Object. prototype. hasOwnProperty; var toString = Object. prototype. toString; var class2type ={}; var noop = function () {}; var AS = function () {If (this = w) {return new AS (arguments) ;}else {console.info (this) ;}};. prototype = {constructor: AS};. fn =. prototype;. extend = function () {var args = arguments; if (args. length = 2) {var target = args [0]; var source = args [1]; for (var attr in source) {target [attr] = source [attr] ;};} else {for (var I = 0, len = args. length; I <len; I ++) {var obj = args [I]; for (var attr in obj) {AS [attr] = Obj [attr] ;};};};/* AMD module starts */var modules ={}; function getEmptyModule () {return {deps: [], offers: [], state: 0, factory: noop}; function getCurrentScript (DOC) {if (DOC. currentScript) {return DOC. currentScript. src; // FF, Chrome}; var stack; try {. b. c ();} catch (e) {stack = e. stack; // immediately throw an error to get the current file path if (! Stack & window. opera) {stack = String (e); if (! Stack & window. opera) {stack = (String (e ). match (/of linked script \ S +/g) | []). join ("") ;};}; if (stack) {stack = stack. split (/[@]/g ). pop (); // get the last row. The last space or part of the stack after @ = stack [0] = "("? Stack. slice (1,-1): stack; return stack. replace (/(: \ d + )?: \ D + $/I, ""); // remove the row number and the starting position of the Error Character} // IEvar nodes = head. getElementsByTagName ("script"); for (var I = 0, node; node = nodes [I ++];) {if (node. readyState = 'interactive ') {return node. src ;};}}function getModuleName (url) {return url. substring (url. lastIndexOf ('/') + 1, url. lastIndexOf ('. js ');} function require (list, factory) {var loaded = 0; var requires = list. length; var args = []; var id = getCurrent Script (DOC); lele.info ('load' + getModuleName (id) + 'module dependency '+ list + 'module') var module = modules [id]? Modules [id]: getEmptyModule (); module ['factory '] = factory; modules [id] = module; for (var I = 0; I <list. length; I ++) {var depId = basePath + list [I] + '. js'; modules [depId] = modules [depId]? Modules [depId]: getEmptyModule (); module ['deps']. push (depId); if (modules [depId] & modules [depId]. state = 2) {console.info (getModuleName (depId) + 'dependency loaded ahead of schedule '); modules [depId]. offers. push (id); loaded ++; args. push (modules [depId]. exports); // The dependent module is being loaded.} else if (modules [depId] & modules [depId]. state = 1) {lele.info (getModuleName (depId) + 'dependency loading '); modules [depId]. offers. push (id); // This dependency module has never been loaded} else {// LoadJS loads the module js. The module js calls define, define also loads the dependencies required by this module by require // so that the function enters recursive tracing and loads all direct and indirect dependencies of this module on eagle.info ('loading the dependency module for the first time '+ getModuleName (depId )); modules [depId]. offers. push (id); loadJS (depId) ;};}; if (loaded === requires) {module. factory. apply (null, args); module. state = 2 ;};}; window. require =. require = require; function loadJS (url) {var module = modules [url]; var node = DOC. createElement ('script'); node. onload = Node. onreadystatechange = function () {if (/loaded | complete/I. test (node. readyState) |! Node. readyState) {};}; node. src = url; head. insertBefore (node, head. firstChild); module. state = 1; // lele.info ('loading module '+ getModuleName (url) ;}; function findFishedModules (url) {var ret = []; var deped = modules [url]; var moduleIds = deped. offers; for (var I = 0; I <moduleIds. length; I ++) {var id = moduleIds [I]; var deps = modules [id]. deps; var flag = false; for (var j = 0; j <deps. length; j ++) {var dep = Modules [deps [j]; if (dep. state = 2 | deps [j] = url) {flag = true ;}; if (dep. state! = 2) {flag = false; break ;};}; if (flag) {// lele.info ('module '+ getModuleName (id) + 'available'); ret. push (id) ;};}; return ret ;}; function fireFactory (root) {lele.info ('lookup depends on '+ getModuleName (root) + 'module installation status'); var finshedIds = findFishedModules (root); for (var I = 0; I <finshedIds. length; I ++) {var module = modules [finshedIds [I]; console.info (getModuleName (finshedIds [I]) + 'All dependencies of the module can be installed, callback function can be executed '); var exports = module. factory. apply (null, getDepsModules (module. deps); module. state = 2; if (exports) {module. exports = exports; lele.info ('import' + getModuleName (finshedIds [I]) + 'module');} else {break ;}; fireFactory (finshedIds [I]) ;};}; function getDepsModules (deps) {var args = []; for (var I = 0; I <deps. length; I ++) {var dep = deps [I]; args. push (modules [dep]. exports) ;}; return args ;}; function define (deps, factory) {var id = getCurrentScript (DOC ); // if this module is not dependent, immediately install this module if (deps. length = 0) {modules [id]. exports = factory. apply (null); modules [id]. state = 2; // from the dependent leaves, find a series of trigger installation lele.info ('module '+ getModuleName (id) + 'Load finished'); fireFactory (id ); return ;}; require (deps, function () {var _ deps = []; for (var I = 0; I <deps. length; I ++) {_ deps. push (basePath + deps [I] + '. js') ;}; modules [id]. exports = factory. apply (null, getDepsModules (_ deps); modules [id]. state = 2; lele.info ('module '+ getModuleName (id) + 'Load completed'); fireFactory (id) ;}; window. define =. define = define;/* AMD module end * // exposes the AS function w. $ = w. AS = AS;}) (self, self.doc ument );



Why AMD module?

The basic premise of a modular system is to allow the creation of encapsulated code snippets, that is, the so-called module definition. The dependency definition between this module and other modules can be used by other modules. The output functions provided by these modules are carefully used. AMD meets the above requirements, set the dependency module as the callback function parameter to asynchronously load the dependent modules before the module code is executed. AMD also provides a plug-in system for loading non-AMD resources. Although there are other alternative load JavaScript methods, using script elements to load JavaScript has unique advantages, including performance and debugging reduction (especially in some older browsers) and cross-origin support. Therefore, AMD is committed to providing optimal browser-based development experience. The AMD format provides several key benefits. First, it provides a compact way to declare dependencies. By defining module dependencies through a simple string array, developers can easily list a large number of module dependencies at a low cost. AMD helps eliminate the need for global variables. Each module defines its dependent modules and output functions through local variable reference or return objects. Therefore, a module can define its functions and interact with other modules without introducing global variables. AMD also encouraged high-performance coding practices by ing dependencies into local variables. Without AMD module loaders, traditional JavaScript code must rely on nested objects to "name" The given script or module. If you use this method, you usually need to access a function through a set of attributes, which causes global variable search and multiple attribute searches, added additional development work and reduced program performance. By adding module Dependencies

How to use javascript to implement module dragging?

1. Drag layer:

<Div id = "div1" style = "position: absolute; background-color: #0064c2; width: 150px; height: 150px;" onmousedown = "MoveStart (this, event) "> </div>

<Script>
Function MoveStart (o, event ){
Var oX = event. clientX-o.offsetLeft;
Var oY = event. clientY-o.offsetTop;

Document. attachEvent ("onmousemove", MoveIt );
Document. attachEvent ("onmouseup", MoveStop );

Event. cancelBubble = true;
Event. returnValue = false;

Function MoveIt (e ){
E = window. event;
O. style. left = (e. clientX-oX) + 'px ';
O. style. top = (e. clientY-oY) + 'px ';

Event. cancelBubble = true;
}

Function MoveStop (){
Document. detachEvent ("onmouseup", MoveStop );
Document. detachEvent ("onmousemove", MoveIt );
}
Event. cancelBubble = true;
}
</Script>

2. Turn off the browser and move the layer to the position after the drag.
You only need to store the current location of the record layer in the database when the user exits. The next time the user opens this page, the location of the read layer from the database is displayed.

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.