ITeye博客

针对之前bingo发布的一个js loader工具进行的改进【bug已修正】

ajaxgo · 2007-12-18 14:36 · Web前端 · EXT · prototype · Markdown

首先很感谢bingo,用非常新颖的思路,实现了这么一个js的loader工具。往外抛异常阻止函数运行,并在加载完后继续运行caller的做法,让人眼前一亮。不得不佩服js的世界是如此的奇妙。

在阅读bingo的js loader,获得启发的同时,也对其中的代码功能做了一些调整。例如,添加了绑定事件机制,可以预先绑定需要在加载(loaded)完后触发的操作(事件一共有5类)。规范了消息队列的实现,bingo的实现中,把消息队列耦合的太紧密。所以独立实现了一个消息队列,在loader中使用等等。整个代码经过重写,并加了注释,方便爱好者学习和探讨,也希望大家反馈bug。并且允许在include时,设置caller的scope和arguments,这样就可以在一般的函数中,比如实例方法(而不只是在匿名函数)使用include。因为,bingo的实现中,在调用caller时,只是简单的运行caller,如果在有需要作用域和需要参数传递的函数中,会失去原本的作用域和传递进来的参数。

最后,还是非常感谢bingo!

代码如下(代码下载在最后):

js 代码

  1. var jsLoader=new function() {
  2. /*
  3. * const
  4. */
  5. this.NAMESPACE_TYPE={
  6. CLASS:'class',
  7. INTERFACE:'interface',
  8. OBJECT:'object'
  9. };
  10. this.LOADMODE_TYPE={
  11. PACKAGE:'package',
  12. FILE:'file',
  13. DYNAMIC:'dynamic'
  14. };
  15. this.ERROR_LEVEL={
  16. INFO:'@jsadk:',
  17. DEBUG:'*@jsadk:',
  18. FATAL:'!*@jsadk:',
  19. THROWS:'^!*@jsadk:'
  20. };
  21. this.ERRORS={};
  22. /*
  23. * private member
  24. */
  25. var _this=this;
  26. var _version='1.0a';
  27. var _libPath='./';
  28. var _errLv=this.ERROR_LEVEL.FATAL;
  29. var _loadmode=this.LOADMODE_TYPE.PACKAGE;
  30. var _packages={};
  31. /*
  32. * getter and setter
  33. */
  34. this.getVersion=function() {
  35. return _version;
  36. };
  37. this.getLibPath=function() {
  38. return _libPath;
  39. };
  40. this.setLibPath=function(libPath) {
  41. _libPath=libPath;
  42. };
  43. this.getLoadMode=function() {
  44. return _loadmode;
  45. };
  46. this.setLoadMode=function(loadmode) {
  47. _loadmode=loadmode;
  48. };
  49. this.getErrLevel=function() {
  50. return _errLv;
  51. }
  52. this.setErrLevel=function(level) {
  53. _errLv=level;
  54. };
  55. /*
  56. * register packages infos
  57. */
  58. /**
  59. * 增加包信息
  60. * @param {Object} root
  61. * @param {Hash} pks
  62. */
  63. var _addPKGs=function(root,pks) {
  64. for (var pk in pks) {
  65. if (typeof pks[pk]=='string') {
  66. root[pk]=_this.Util.initVar(root[pk],pks[pk]);
  67. } else if(typeof pks[pk]=='object') {
  68. root[pk]=_this.Util.initVar(root[pk],{});
  69. _addPKGs(root[pk],pks[pk]);
  70. }
  71. }
  72. };
  73. /**
  74. * 获得注册的包信息
  75. * @param {String|Object} pack
  76. */
  77. this.getPKGs=function(pack) {
  78. return _this.Util.eval(pack,_packages);
  79. };
  80. /**
  81. * 注册包信息
  82. * @param {Hash} pkgs
  83. * @param {String} ns
  84. */
  85. this.regPKGs=function(pkgs,ns) {
  86. var size=arguments.length;
  87. var ns=ns.split('.');
  88. var root=_packages;
  89. for (var i=0;i
  90. root=root[ns[i]]=_this.Util.initVar(root[ns[i]],{});
  91. }
  92. _addPKGs(root,pkgs);
  93. };
  94. /*
  95. * catch the window error
  96. */
  97. window.onerror=function() {
  98. if (arguments[0].indexOf(_errLv)>-1) {
  99. return false;
  100. } else {
  101. return true;
  102. }
  103. };
  104. };
  105. with(jsLoader) {
  106. /*
  107. * utility methods
  108. */
  109. jsLoader.Util={
  110. /**
  111. * 一个空函数的引用
  112. */
  113. emptyFunction:function() {},
  114. /**
  115. * 在给定的scope中执行代码
  116. * @param {String} obj
  117. * @param {Object} scope[default=window]
  118. */
  119. eval:function(obj,scope) {
  120. scope=(scope==null)?window:scope;
  121. if (typeof obj=='string') {
  122. try {
  123. with(scope) {
  124. obj=eval(obj);
  125. }
  126. } catch (e) {
  127. return undefined;
  128. }
  129. }
  130. return obj;
  131. },
  132. /**
  133. * 检查在给定的scope中对象是否存在
  134. * @param {String|Object} obj
  135. * @param {Object} scope[default=window]
  136. */
  137. exist:function(obj,scope) {
  138. return (typeof this.eval(obj,scope)=='undefined'?false:true);
  139. },
  140. /**
  141. * 用给定的值initVal,初始化变量obj,并返回obj。如果obj不为undefined,则直接返回obj
  142. * @param {Object} obj
  143. * @param {Object} initVal
  144. */
  145. initVar:function(obj,initVal) {
  146. if (typeof obj=='undefined') {
  147. obj=initVal;
  148. }
  149. return obj;
  150. },
  151. /**
  152. * 用source扩展destination,并返回destination。
  153. * fProperty和fValue用来筛选source中的属性和值
  154. * @param {Object} destination
  155. * @param {Object} source
  156. * @param {Function} fProperty(property,destination)[scope=source]
  157. * @param {Function} fValue(value,property,destination)[scope=source]
  158. */
  159. extend:function(destination,source,fProperty,fValue) {
  160. for (var property in source) {
  161. var _property=(fProperty || Util.emptyFunction).call(source,property,destination);
  162. if (_property!=false) {
  163. var _value=(fValue!=null?
  164. fValue.call(source,source[property],property,destination):
  165. source[property]);
  166. destination[typeof _property=='string'?_property:property]=_value;
  167. }
  168. }
  169. return destination;
  170. }
  171. };
  172. /*
  173. * extends Array
  174. */
  175. (function() {
  176. Util.extend(Array.prototype,{
  177. first:function() {
  178. return this[0];
  179. },
  180. last:function() {
  181. return this[this.length-1];
  182. },
  183. /**
  184. * 给出element在队列中所处的位置索引(第一个),如果不存在则返回-1。参数struct为true是进行严格比较
  185. * @param {Object} element
  186. * @param {Boolean} struct[default=false]
  187. */
  188. indexOf:function(element,struct) {
  189. var size=this.length;
  190. for (var i=0;i
  191. if ((struct && this[i]===element) ||
  192. (!struct && this[i]==element)) {
  193. break;
  194. }
  195. }
  196. return (i==size?-1:i);
  197. },
  198. /**
  199. * 在索引index处插入元素element1,element2,....
  200. * @param {Number} index
  201. */
  202. insertAt:function(index) {
  203. var args=[index,0];
  204. var size=arguments.length;
  205. for (var i=1;i
  206. args.push(arguments[i]);
  207. }
  208. this.splice.apply(this,args);
  209. },
  210. /**
  211. * 删除索引index处的size个元素,并返回删除的元素数组
  212. * @param {Number} index
  213. * @param {Number} size[opt=1]
  214. */
  215. deleteAt:function(index,size) {
  216. result=this.splice(index,size || 1);
  217. return result;
  218. },
  219. /**
  220. * 清空队列
  221. */
  222. clear:function() {
  223. this.length=0;
  224. }
  225. });
  226. })();
  227. /**
  228. * 事件队列,用于注册和注销事件。并触发对应事件
  229. */
  230. jsLoader.EventQueue=(function() {
  231. Util.extend(ERRORS,{
  232. 'EventQueue.NO_SUCH_EVENT':ERROR_LEVEL.DEBUG+'no such a event',
  233. 'EventQueue.ALEADY_EXIST':ERROR_LEVEL.DEBUG+'the message is already exsited!'
  234. });
  235. var constructor=function(event) {
  236. this._queue={};
  237. this.EVENT={};
  238. for (var e in event) {
  239. this.EVENT[event[e]]=true;
  240. this._queue[event[e]]=[];
  241. }
  242. };
  243. Util.extend(constructor.prototype,{
  244. /**
  245. * 触发队列中,对应事件event的消息。参数dispose为ture时,将在触发完后删除该事件的所有消息。
  246. * @param {String} event
  247. * @param {Boolean} dispose[default=false]
  248. * @param {Array} args[default=[]]
  249. */
  250. dispatch:function(event,dispose,args) {
  251. if (this.EVENT[event]) {
  252. var messages=this._queue[event];
  253. var size=messages.length;
  254. try {
  255. for (var i=0;i
  256. messages[i++].apply(messages[i++],messages[i++].concat(args || []));
  257. }
  258. } catch(e) {
  259. throw new Error(ERROR_LEVEL.DEBUG+e.message);
  260. } finally {
  261. if (dispose) {
  262. this._queue[event].clear();
  263. }
  264. }
  265. } else {
  266. throw new Error(ERRORS['EventQueue.NO_SUCH_EVENT']+':'+event);
  267. }
  268. },
  269. /**
  270. * 注册事件event的消息message。scope和args参数指定了消息调用时的作用域和参数。
  271. * @param {String} event
  272. * @param {Function} message
  273. * @param {Object} scope[default=window]
  274. * @param {Array} args[default=[]]
  275. */
  276. on:function(event,message,scope,args) {
  277. if (this.EVENT[event]) {
  278. if (this._queue[event].indexOf(message)==-1) {
  279. this._queue[event].push(message);
  280. this._queue[event].push(scope || window);
  281. this._queue[event].push(args || []);
  282. } else {
  283. throw new Error(ERRORS['EventQueue.ALEADY_EXIST']+':'+event);
  284. }
  285. } else {
  286. throw new Error(ERRORS['EventQueue.NO_SUCH_EVENT']+':'+event);
  287. }
  288. },
  289. /**
  290. * 注销事件event的小心message
  291. * @param {String} event
  292. * @param {Function} message
  293. */
  294. un:function(event,message) {
  295. var index;
  296. if (this.EVENT[event] && (index=this._queue[event].indexOf(message))!=-1) {
  297. this._queue[event].deleteAt(index,3);
  298. } else {
  299. throw new Error(ERRORS['EventQueue.NO_SUCH_EVENT']+':'+event);
  300. }
  301. }
  302. });
  303. return constructor;
  304. })();
  305. /*
  306. * a class of message queue, used to invoke messages orderly
  307. */
  308. jsLoader.MessageQueue=(function() {
  309. var constructor=function() {
  310. this._queue=[];
  311. this._listened=null;
  312. }
  313. Util.extend(constructor.prototype,{
  314. /**
  315. * 队列监听器,识别队列中是否有可以产生的消息
  316. */
  317. _listen:function() {
  318. var _this=this;
  319. if (this._listened) {
  320. if (this._queue.length==0) {
  321. setTimeout(function() {
  322. _this._listen()
  323. },500);
  324. } else {
  325. this.inform();
  326. }
  327. }
  328. },
  329. /**
  330. * 启动监听器
  331. */
  332. startListen:function() {
  333. this._listened=true;
  334. this._listen();
  335. },
  336. /**
  337. * 停止监听器
  338. */
  339. stopListen:function() {
  340. this._listened=false;
  341. },
  342. /**
  343. * 通知消息队列,另起产生队列头部的一个消息
  344. */
  345. inform:function() {
  346. if (this._queue.length==0) {
  347. this._listen();
  348. return;
  349. } else {
  350. var message=this._queue.shift();
  351. var scope=this._queue.shift();
  352. var args=this._queue.shift();
  353. try {

评论(7)

  1. #7 楼 · rain16881 · 2008-04-21 13:16

    我用了之后是可以按自己想的顺序加载了..

    不过.性能是一个好大的问题.

    加上..我在js 的有调用的..一个也不要用.

  2. #6 楼 · rain16881 · 2008-04-21 11:34

    有的ext desktop就有一个js加载顺序的问题.

    希望能用你的js loader解决

  3. #5 楼 · brull · 2008-01-14 12:24
  4. #4 楼 · ajaxgo · 2008-01-14 09:10
  5. #3 楼 · ajaxgo · 2008-01-14 09:09

    sun2grit writes:

    能举几个简单的调用示例吗?

    下载的代码里面有示例

  6. #2 楼 · brull · 2008-01-12 20:54
  7. #1 楼 · sun2grit · 2008-01-12 18:34

    能举几个简单的调用示例吗?

评论功能维护中,当前仅展示历史评论。