sea.js的應用
模塊化:
將Js代碼按模塊化分開,提升了代碼的重用性;
seaJs的好處:
解決了文件的依賴
解決了變量名的衝突
seaJs的使用
一、定義模塊
define(function(require,exports,module)){
require:引入一個模塊
如:var _msg = require("msg");
exports:輸出一個模塊
如:exports.msg = function(){
alert("ok");
}
module:批量輸出模塊(不多用)
}
二、使用一個模塊
seajs.use("模塊名",function(mod){
//code
})
使用多個模塊
seajs.use(["a","b",···],function(mod1,mod2···){})
效果:添加一我的的姓名,年齡和通信方式
框架:
html代碼:css
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title>SeaJs Test</title> 6 <script src="../js/sea.js"></script> 7 <script> 8 seajs.use("init",function(init){ 9 init.init(); 10 }) 11 </script> 12 </head> 13 <body> 14 <div class="main"> 15 <h1>信息</h1> 16 <ul> 17 <li id="s1"></li> 18 <li id="s2"></li> 19 <li id="s3"></li> 20 </ul> 21 </div> 22 </body> 23 </html>
init.js代碼:
1 define(function(require,exports,module){ 2 var man = require("man"); 3 var css = require("../css/main.css"); 4 5 var $ = function(id){ 6 return document.getElementById(id); 7 }; 8 9 exports.init = function(){ 10 var s1 = $("s1"); 11 var s2 = $("s2"); 12 var s3 = $("s3"); 13 14 var name = man.getName(); 15 var age = man.getAge(); 16 var msg = man.say(); 17 18 s1.innerHTML = name; 19 s2.innerHTML = age; 20 s3.innerHTML = msg; 21 22 } 23 })
man.js代碼:
1 define(function(require,exports,module){ 2 var msg = require("msg"); 3 4 var _name = "tom"; 5 var _age = "20"; 6 7 exports.myName = _name; 8 9 exports.say = function(){ 10 return msg.getMsg(); 11 }; 12 13 exports.getName = function(){ 14 return _name; 15 }; 16 17 exports.getAge = function(){ 18 return _age; 19 } 20 })
msg.js代碼:
1 define(function(require,exports,module){ 2 var _msg = "not set msg!"; 3 4 exports.setMsg = function(msg){ 5 _msg = msg; 6 } 7 exports.getMsg = function(){ 8 return _msg; 9 } 10 });