动手写一个JavaScript模块

本文目录结构

--[resource]
  --[html]
  --[js]
    --[common]
      --jquery.js
      --underscore.js
      --myModule.js
      --otherModule.js
    --require.js

其中myModule.js是本文要实现的一个模块,otherModule.js为使用myModule的一个模块。

实现一个模块

先实现一个无比简单的模块"myModule":

define ("myModule", ["jquery", "underscore"], function($, _) { //声明一个模块,模块名字为"myModule", "jquery"和"underscore"为该模块依赖的模块, "$"和"_"为所依赖模块的返回句柄,即可以使用该句柄使用其他模块,尽管本例中实际上并不需要,这里只为示例

	function multiply(a, b) { //本模块实现的求两数乘积函数
		return a * b; 
	}
	
	function sum(a, b) { //本模块实现的求两数和的函数
		return a + b;
	}
	
	return { //使用return 定义本模块对外呈现的内容,可以方便的把模块内部实现与其他模块解藕
		multiplyAPI : multiply,
		sumAPI      : sum,
	}
	
})

假设该文件名为"myModule.js",存放于项目目录module/commom/中。

配置模块

写完一个模块,接下来就在require 配置文件中配置一下,方便后续使用。

require.config({

	"baseUrl" : "/resource/js/"
	"paths"   : {
	  "jquery"     : "module/common/jquery.js",
	  "underscore" : "module/common/underscore.js",
	  "myModule"   : "module/common/myModule.js"
  }
});

该配置实际上记录的是模块名字及模块所在位置的对应关系,这样在使用模块时只需使用名字,而不用关心模块位置了。

html中使用自定义模块

<!DOCTYPE html>
<html lang="zh-CN">
<head>
	...
</head>
	
<body>
  ...
  <script src="resource/js/require.js"></script>
  require(["jquery","underscore", "myModule"],function($, _, myModuleHandler){
    myModuleHandler.multiply(1, 2);
  })
</body>
	
</html>

“myModuleHandler”即模块执行结束后返回的句柄,使用该句柄操作模块对外开放的API.

其他模块使用自定义模块

其他模块使用自定义模块,跟"myModule"模块使用"jquery"库方式一样。

比如其他模块"otherModule.js"需要使用"myModule"。 html中应该这么写

<!DOCTYPE html>
<html lang="zh-CN">
<head>
	...
</head>
	
<body>
  ...
  <script src="resource/js/require.js"></script>
  require(["jquery","underscore", "myModule", "otherModule"],function($, _, myModuleHandler, otherModuleHandler){
    otherModuleHandler.fun(); //otherMoudle实现的方法
  })
</body>
	
</html>

当然使用之前,也需要在require.js中配置,这里不再赘述。

otherModule.js应该这么写

define ("otherModule", ["jquery", "underscore", "myModule"], function($, _, myModuleHandler) { 

	function fun() {
		return myModuleHandler.sum(1, 2); 
	}
	
	return { 
		fun : multiply
	}
	
})

看,跟使用jquery方式完全一样的。

猜你喜欢

转载自my.oschina.net/renhc/blog/1819822