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代码:
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 });
时间: 2024-12-21 07:54:23