sea.js的应用
模块化:
将Js代码按模块化分开,提高了代码的重用性;
seaJs的好处:
解决了文件的依赖
解决了变量名的冲突
seaJs的使用
1、定义模块
define(function(require,exports,module)){
require:引入一个模块
如:var _msg = require("msg"); exports:输出一个模块
如:exports.msg = function(){
alert("ok");
} module:批量输出模块(很少用)
}
2、使用一个模块
seajs.use("模块名",function(mod){
//code
})
使用多个模块
seajs.use(["a","b",···],function(mod1,mod2···){}) 效果:添加一个人的姓名,年龄和通讯方式
框架:
html代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>SeaJs Test</title>
<script src="../js/sea.js"></script>
<script>
seajs.use("init",function(init){
init.init();
})
</script>
</head>
<body>
<div class="main">
<h1>信息</h1>
<ul>
<li id="s1"></li>
<li id="s2"></li>
<li id="s3"></li>
</ul>
</div>
</body>
</html>
init.js代码:
define(function(require,exports,module){
var man = require("man");
var css = require("../css/main.css"); var $ = function(id){
return document.getElementById(id);
}; exports.init = function(){
var s1 = $("s1");
var s2 = $("s2");
var s3 = $("s3"); var name = man.getName();
var age = man.getAge();
var msg = man.say(); s1.innerHTML = name;
s2.innerHTML = age;
s3.innerHTML = msg; }
})
man.js代码:
define(function(require,exports,module){
var msg = require("msg"); var _name = "tom";
var _age = "20"; exports.myName = _name; exports.say = function(){
return msg.getMsg();
}; exports.getName = function(){
return _name;
}; exports.getAge = function(){
return _age;
}
})
msg.js代码:
define(function(require,exports,module){
var _msg = "not set msg!"; exports.setMsg = function(msg){
_msg = msg;
}
exports.getMsg = function(){
return _msg;
}
});