附:seajs源码包下载
1.seajs源码引入
将下好的sea.js文件放入你的html等文件中。
<script type="text/javascript" src="js/sea.js"></script>
我的文件目录树如下:
2.seajs模块定义define
define的回调函数中有三个参数:
require是请求外部文件
explores相当于interface接口便于外部调用
module是当前模块的信息
//这里只是定义了一个模块(module.js文件),内部的函数相当于一个闭包
define(function(require,explorts,module){
var name = "charles";//声明了一个变量
function foo(){ // 模块中声明了一个foo函数
alert("hello world");
}
});
3.seajs模块向外部模块提供接口explorts
<script type="text/javascript">
define(function(require,explorts,module){
var name = "charles";
function foo(){
alert("hello world");
}
explorts.name = name;//只需要将该属性名称(name)赋给explorts的相同属性(name)即可。
explorts.foo = foo;//函数也是同理
});
</script>
4.seajs模块引用外部模块seajs.use
引用外部模块时需要两个参数,
参数1(必选):外部模块的url
参数2(可选):回调函数,回调函数中传入explorts对象
<script type="text/javascript">
//引用外部文件时,需要两个参数
seajs.use('./js/module.js',function(explorts){
explorts.foo();
});
</script>
需要注意的一点是:一定要注意引用的路径问题!
例如:
seajs.use('js/module.js');
结果路径错误: 默认根目录为sea.js所在的目录(即js文件夹下)
5.seajs模块依赖require
require在define中直接添加;
返回值:是一个explorts对象,因此可以在其后面直接使用模块中的方法
require('../js/tool.js').foo();
以下是各个文件的样例代码:
module.js文件
define(function(require,explorts,module){
require('../js/tool.js'); //添加一个tool.js工具模块
var obj = $().getId('div');//返回一个Tool对象
console.log(obj);//打印在控制台,附图可见
var name = "charles";
function foo(){
alert("hello world");
}
explorts.name = name;
explorts.foo = foo;
});
tool.js文件
//重载$符号,模拟jquery写法,如果在Tool中加入_this参数就更完美了
var $ = function(){
return new Tool();
}
function Tool(){
this.elements = [];
}
Tool.prototype.getId = function(id){
this.elements.push(document.getElementById(id));
return this;
}
index.html文件
<!doctype html>
<html>
<script type="text/javascript" src="js/sea.js"></script>
<script type="text/javascript">
//引用外部文件时,需要两个参数
seajs.use('./js/module.js',function(explorts){
explorts.foo();
});
</script>
<head>
<div id="div">
</div>
</head>
</html>
输出的结果为:
注意,require是在define中添加的,在use中不能使用。