"Seajs Source Analysis" 2. Tool Method 1

Source: Internet
Author: User
Tags emit unique id vars

Sea.js:

var seajs = Global.seajs = {  // The current version of Sea.js being used  Versi On: "@VERSION"}var data = Seajs.data = {}

The code defines a SEAJS variable and exposes it to the global, and the variable now has only one value that is the version number variable

In addition, a data variable is defined, which is followed by the

Util-lang.js

/** * util-lang.js-the minimal language enhancement*/functionIstype (type) {return function(obj) {return{}.tostring.call (obj) = = "[Object" + Type + "]"  }}varIsObject = Istype ("Object")varisstring = Istype ("String")varIsArray = Array.isarray | | Istype ("Array")varIsfunction = Istype ("Function")varisundefined = Istype ("Undefined")var_cid = 0functioncid () {return_cid++}

Here is a function to determine the object type, here is an evolutionary process is interesting, if interested can refer to the next Yuber GitHub blog

The Cid method is used to generate a unique ID, which is followed by a

Util-events.js

/** * Util-events.js-the minimal events support*/varEvents = Data.events = {}//Bind EventSeajs.on =function(name, callback) {varList = Events[name] | | (Events[name] =[]) List.push (callback)returnSeajs}//Remove event. If ' callback ' is undefined, remove all callbacks for the//event. If ' event ' and ' callback ' is both undefined, remove all callbacks//For all eventsSeajs.off =function(name, callback) {//Remove *all* Events  if(! (Name | |callback)) {Events= Data.events = {}    returnSeajs}varList =Events[name]if(list) {if(callback) { for(vari = list.length-1; I >= 0; i--) {        if(List[i] = = =callback) {List.splice (i,1)        }      }    }    Else {      DeleteEvents[name]}} returnSeajs}//Emit event, firing all bound callbacks. Callbacks receive the same//arguments as ' emit ' does, apart from the event namevarEmit = Seajs.emit =function(name, data) {varList =Events[name], fnif(list) {//Copy callback lists to prevent modificationList =List.slice ()//Execute Event Callbacks     while(fn =List.shift ()))  {fn (data)}} returnSeajs}

An event handling mechanism that is used to register events, add callback functions for the specified array of events, off to remove events, remove all callback functions for events if no event name and callback function is specified, delete all callback functions for the event if no callback function is specified, Emit functions used to trigger events and event bindings

Util-path.js

/** * util-path.js-the utilities for operating path such as ID, URI*/varDirname_re =/[^?#]*\//varDot_re =/\/\.\//gvarDouble_dot_re =/\/[^/]+\/\.\.\//varDouble_slash_re =/([^:/]) \/\//g//Extract The directory portion of a path//dirname ("A/b/c.js?t=123#xx/zz") ==> "a/b/"//REF:HTTP://JSPERF.COM/REGEX-VS-SPLIT/2functiondirname (path) {returnPath.match (dirname_re) [0]}//canonicalize a path//Realpath ("http://test.com/a//./b/../c") ==> "HTTP://TEST.COM/A/C"functionRealpath (path) {///a/b/./c/./d ==>/a/b/c/dPath = Path.replace (Dot_re, "/")  //a/b/c/. /.. /d ==> a/b/. /d ==> A/d   while(Path.match (double_dot_re)) {path= Path.replace (Double_dot_re, "/")  }  //a//b/c ==> a/b/cPath = Path.replace (Double_slash_re, "$1/")  returnpath}//Normalize an ID//normalize ("path/to/a") ==> "Path/to/a.js"//notice:substring is faster than negative slice and RegExpfunctionNormalize (path) {varLast = Path.length-1varLASTC =Path.charat (last)//If The URI ends with ' # ', just return it without ' # '  if(LASTC = = = "#") {    returnPath.substring (0, last)} return(path.substring (last-2) = = = ". js" | |Path.indexof ("?") > 0 | |path.substring ( last-3) = = = ". css" | |LASTC=== "/") ? Path:path + ". js"}varPaths_re =/^ ([^/:]+) (\/.+) $/varVars_re =/{([^{]+)}/gfunctionParsealias (ID) {varAlias =Data.aliasreturnAlias && isstring (Alias[id])?Alias[id]: id}functionparsepaths (ID) {varpaths =data.pathsvarmif(Paths && (M = Id.match (paths_re)) && isstring (paths[m[1]]) {ID= Paths[m[1]] + m[2]  }  returnID}functionParsevars (ID) {varVARs =Data.varsif(VARs && Id.indexof ("{") >-1) {ID= Id.replace (Vars_re,function(M, key) {returnIsstring (Vars[key])?Vars[key]: M})}returnID}functionParsemap (URI) {varMap =Data.mapvarRET =URIif(map) { for(vari = 0, len = map.length; i < Len; i++) {      varRule =Map[i] ret= isfunction (rule)?(rule (URI)||URI): Uri.replace (rule[0], rule[1])      //Only apply the first matched rule      if(Ret!== URI) Break    }  }  returnret}varAbsolute_re =/^\/\/.|:\ //varRoot_dir_re =/^.*?\/\/.*?\//functionaddbase (ID, Refuri) {varretvarFirst = Id.charat (0)  //Absolute  if(Absolute_re.test (ID)) {ret=ID}//Relative  Else if(First = = = ".")) {ret= Realpath (Refuri dirname (Refuri): DATA.CWD) +ID)}//Root  Else if(First = = = "/") {    varm =Data.cwd.match (root_dir_re) RET= L ^ M[0] + id.substring (1): ID}//top-level  Else{ret= Data.base +ID}//Add default protocol when URI begins with "//"  if(Ret.indexof ("//") = = = 0) {ret= Location.protocol +ret}returnret}functionId2uri (ID, Refuri) {if(!id)return""ID=Parsealias (ID) ID=parsepaths (ID) ID=Parsevars (ID) ID=normalize (ID)varURI =addbase (ID, Refuri) URI=Parsemap (URI)returnURI}varDoc =DocumentvarCWD =DirName (Doc. URL)varScripts =doc.scripts//recommend to add ' Seajsnode ' ID for the ' sea.js ' script elementvarLoaderscript = Doc.getelementbyid ("Seajsnode") | |Scripts[scripts.length-1]//When ' Sea.js ' was inline, set Loaderdir to current working directoryvarLoaderdir = DirName (getscriptabsolutesrc (loaderscript) | |CWD)functiongetscriptabsolutesrc (node) {returnNode.hasattribute?//NON-IE6/7NODE.SRC://See http://msdn.microsoft.com/en-us/library/ms536429 (vs.85). aspxNode.getattribute ("src", 4)}//For developersSeajs.resolve = Id2uri

This code is used for path processing:

First, a set of regular expressions is defined for the path analysis

DirName function: Gets the directory portion of a set of paths, such as dirname ("A/b/c.js?t=123#xx/zz"), the result is a/b

Realpath function: The specification of a set of paths, such as Realpath ("http://test.com/a//./b/../c") ==> "http://test.com/a/c", is the./. /and//convert to canonical path

Normalize function: Canonical suffix of a set of paths, such as normalize ("path/to/a") ==> "Path/to/a.js".

Parsealias function: path alias processing, returning aliases based on alias ID

Parsepaths: To parse the path in the configuration, refer to config usage

Parsevars: Parsing variables in a configuration

Parsemap: Resolving a map in a configuration

Addbase: Converting a path to a full path

Id2uri: Convert module ID to true full path

Util-deps.js:

/** * util-deps.js-the parser for dependencies * ref:tests/research/parse-dependencies/test.html*/varRequire_re =/"(?: \ \"| [^"]) * ' | ' (?:\ \ ' | [^ ']) * ' |\/\*[\s\s]*?\*\/|\/(?: \ \\/| [^\/\r\n]) +\/(? =[^\/]) |\/\/.*|\.\s*require| (?:^| [^$]) \brequire\s*\ (\s* (["']) (. +?) \1\s*\)/gvarSlash_re =/\\\\/gfunctionparsedependencies (code) {varRET =[] Code.replace (Slash_re,""). Replace (Require_re,function(M, M1, m2) {if(m2) {Ret.push (m2)}}) returnret}

Require module in parsing module code, that is, dependency module parsing

"Seajs Source Analysis" 2. Tool Method 1

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.