---
title: "针对之前bingo发布的一个js loader工具进行的改进【bug已修正】"
author: "ajaxgo"
date: "2007-12-18T14:36:35Z"
tags: ["EXT", "prototype"]
categories: ["Web前端"]
slug: "bingo-js-loader-bug"
draft: false
lastmod: "2007-12-18T14:36:35Z"
id: 149125
url: "https://ajaxgo.iteye.com/blog/149125"
---

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

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

最后，还是非常感谢bingo！

代码如下（代码下载在最后）：

js 代码

001. var jsLoader=new function() {
002. /*
003. * const
004. \*/
005. this.NAMESPACE\_TYPE={
006. CLASS:'class',
007. INTERFACE:'interface',
008. OBJECT:'object'
009. };
010. this.LOADMODE\_TYPE={
011. PACKAGE:'package',
012. FILE:'file',
013. DYNAMIC:'dynamic'
014. };
015. this.ERROR\_LEVEL={
016. INFO:'@jsadk:',
017. DEBUG:'\*@jsadk:',
018. FATAL:'!\*@jsadk:',
019. THROWS:'^!\*@jsadk:'
020. };
021. this.ERRORS={};
022. /*
023. * private member
024. \*/
025. var \_this=this;
026. var \_version='1.0a';
027. var \_libPath='./';
028. var \_errLv=this.ERROR\_LEVEL.FATAL;
029. var \_loadmode=this.LOADMODE\_TYPE.PACKAGE;
030. var \_packages={};
031. /*
032. * getter and setter
033. \*/
034. this.getVersion=function() {
035. return \_version;
036. };
037. this.getLibPath=function() {
038. return \_libPath;
039. };
040. this.setLibPath=function(libPath) {
041. \_libPath=libPath;
042. };
043. this.getLoadMode=function() {
044. return \_loadmode;
045. };
046. this.setLoadMode=function(loadmode) {
047. \_loadmode=loadmode;
048. };
049. this.getErrLevel=function() {
050. return \_errLv;
051. }
052. this.setErrLevel=function(level) {
053. \_errLv=level;
054. };
055. /*
056. * register packages infos
057. \*/
058. /\**
059. * 增加包信息
060. * @param {Object} root
061. * @param {Hash} pks
062. \*/
063. var \_addPKGs=function(root,pks) {
064. for (var pk in pks) {
065. if (typeof pks\[pk]=='string') {
066. root\[pk]=\_this.Util.initVar(root\[pk],pks\[pk]);
067. } else if(typeof pks\[pk]=='object') {
068. root\[pk]=\_this.Util.initVar(root\[pk],{});
069. \_addPKGs(root\[pk],pks\[pk]);
070. }
071. }
072. };
073. /\**
074. * 获得注册的包信息
075. * @param {String|Object} pack
076. \*/
077. this.getPKGs=function(pack) {
078. return \_this.Util.eval(pack,\_packages);
079. };
080. /\**
081. * 注册包信息
082. * @param {Hash} pkgs
083. * @param {String} ns
084. \*/
085. this.regPKGs=function(pkgs,ns) {
086. var size=arguments.length;
087. var ns=ns.split('.');
088. var root=\_packages;
089. for (var i=0;i
090. root=root\[ns\[i]]=\_this.Util.initVar(root\[ns\[i]],{});
091. }
092. \_addPKGs(root,pkgs);
093. };
094. /*
095. * catch the window error
096. \*/
097. window.onerror=function() {
098. if (arguments\[0].indexOf(\_errLv)&gt;-1) {
099. 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 {