AMD研究,组件的动态加载。

研究了一下dojo的ADM。明白组件的加载机制了。

(function(){
var w = window, d = document;
if(w.fu) return;

var _Class = {
create : function(){
return function(){
this.init.apply(this, arguments);
}
}
},

_each = function(arr, fn){
for(var i = 0; i < arr.length; i++){
if(fn(arr[i], i) === false) break;
}
},

_Map = _Class.create();

_Map.prototype = {
init : function(){
this._array = [];
},
set : function(key, value){
var _exist = false;
_each(this._array, function(item){
if(item.key == key){
_exit = true;
return false;
}
});
if(!_exist) this._array.push({"key":key, "value":value});
},
get : function(key){
var _val;
_each(this._array, function(item){
if(item.key == key){
_val = item.value;
return false;
}
});
return _val;
}
};

var _eval = new Function("return eval(arguments[0]);"),

_ajaxGet = function(url, callback){
var _xhr = w.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
_xhr.open("GET", url, false);
_xhr.setRequestHeader("Accpet", "text/pain");
_xhr.send(null);
if(_xhr.status == 200 || (!location.host && !_xhr.status)){
if(callback) callback(_xhr.responseText);
}else{
console.log("xhrFailed", _xhr.status);
}
return _xhr.resposeText;
},

_getBaseUrl = function(){
var _scripts = d.getElementsByTagName("script"), i = 0, _baseUrl = "./";
while(i < _scripts.length){
var _script = _scripts[i++];
_src = _script.src;
if(_src){
var _match = _src.match(/(((.*)\/)|^)fu\.js(\W|$)/i);
if(_match){
_baseUrl = _match[3];
break;
}
}
}
return _baseUrl;
},

_baseUrl = _getBaseUrl(),

_completeUrl = function(url){
return _baseUrl+"/"+url+".js";
};

w.fu = {
getBaseUrl : function(){
return _baseUrl;
},

loadFiles : new _Map(),

require : function(loadList, fn){
var _self = this;
if(!loadList || loadList.length == 0) return fn();
_each(loadList, function(url){
var _url = _completeUrl(url);
_ajaxGet(_url, function(jsText){
var module = _self.eval(jsText, _url);
_self.loadFiles.set(url, module);
});
});
var _loadListArgs = [];
_each(loadList, function(url){
_loadListArgs.push(_self.loadFiles.get(url));
});
return fn.apply(this, _loadListArgs);
},

define : function(loadList, fn){
return this.require(loadList, fn);
},

eval : function(text, hint){
return _eval(text + "\r\n////@ sourceURL=" + hint);
}
}
})();

dom.js

fu.define([], function(){
return {dom:"dom"};
});

string.js

fu.define([], function(){
return {"string" : "string"};
});

on.js

fu.define([], function(){
return {on:"on"};
});
















你可能感兴趣的:(JavaScript,Dojo)