介紹javascript
1 模塊定義definecss
define(function(require,exports,module){ //require 引入須要的模塊如jquery等 //var $ = require('./jquery'); //exports能夠把方法或屬性暴露給外部 exports.name = 'hi'; exports.hi = function(){ alert('hello'); } //module提供了模塊信息 });
2 使用定義好的模塊seajs.usehtml
<!doctype html> <html> <head> <title>SeaJs Test</title> <meta charset="UTF-8"> <script type="text/javascript" src="seajs/sea.js"></script> <script type="text/javascript"> //第一個參數是模塊標識,即要使用模塊的路徑,這裏是t1.js //第二個參數是一個回調函數 seajs.use('./js/t1',function(t){ t.hi(); }); </script> </head> <body> </body> </html>
3 加載依賴項requirejava
//名稱必須是require,能夠理解爲一個關鍵詞同樣,接收一個參數 var $ = require('./jquery');
4 向外部提供接口exportsjquery
define(function(require,exports,module){ //exports能夠把方法或屬性暴露給外部 exports.name = 'hi'; exports.hi = function(){ alert('hello'); } });
5 當前模塊信息modulegit
這裏只介紹幾個基本的,具體能夠參考https://github.com/seajs/seajs/issues/242github
1 module.id 模塊標識數組
2 module.uri 根據模塊系統的路徑解析規則獲得的模塊絕對路徑函數
3 module.dependencies 表示當前模塊的依賴列表,是一個數組post
4 module.status 當前模塊的狀態,是一個數值
示例
代碼結構
代碼文件
index.html
<!doctype html> <html> <head> <title>SeaJs Test</title> <meta charset="UTF-8"> <script type="text/javascript" src="seajs/sea.js"></script> <script type="text/javascript"> seajs.use('./js/init',function(init){ init.init(); }); seajs.config({ charset: 'utf-8' }); </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; } });
main.css
*{ font-size: 18px; font-family: "Tahoma,Arial,Helvetica,sans-serif"; } .main{ width: 500px; height: 300px; margin: 50px auto; }