今天繼續嘗試seajs 2.3的版本,那作點什麼demo好呢,就來一個簡單是數據模板吧,而後經過其餘一些細節深刻學習javascript
先看看目錄結構,按照官方demo架設
html
index.html只是簡單入口文件和seajs的配置項,最下面有一個seajs.use加載crontroller模塊,而後回調暴露的combine方法java
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>halo sea.js</title> <script type="text/javascript" src="../sea-modules/sea.js"></script> </head> <body> <div id="hello"></div> </body> </html> <script type="text/javascript"> seajs.config({ base : "../sea-modules/", alias : { "jquery" : "jquery.js" } }); seajs.use("../static/crontroller", function(c){ console.log(c.combine()); }); </script>
crontroller模塊,裏面有一些官方的說明和調試,試用了require.async異步加載、require方式加載其餘模塊(數據和模板module)、如何成功加載非CMD標準定義模塊jquery
define(function(require, exports, module) { /* 使用模塊系統內部的路徑解析機制來解析並返回模塊路徑。 * 該函數不會加載模塊,只返回解析後的絕對路徑 */ // console.log( require.resolve("./data.js") ); // console.log( module.id ); // console.log( module.uri ); // exports 是 module.exports 的一個引用 // console.log(module.exports === exports); // 從新給 module.exports 賦值(繼承) // module.exports = new SomeClass(); // exports 再也不等於 module.exports //console.log(module.exports === exports); /* dependencies 是一個數組,表示當前模塊的依賴 */ // console.log(module.dependencies); /* 異步加載模塊,當加載多個模塊可以使用數組形式['./a','./b'] */ require.async('./async'); var data = require('./data'); var temp = require('./temp'); /* 終於可以加載 */ var halo = require('./hello'); console.log(halo); exports.combine = function() { return temp.replace("{{name}}", data.name); }; });
data模塊,嘗試了在同一份文件定義多個define,結果後者會覆蓋前者! git
若是以後項目優化需用到合併js文件解決http連接數問題,看看官方seajs-combo插件和官方解析module.id和module.uri的說明可能會更加清晰github
define({name:"jack"}); /* 估計內部會判斷參數類型,當是function類型就執行, * 而後將返回結果綁到exports對象上,與exports.name = "jack"效果同樣; * 只是寫法不同 */ /* define(function(require) { return { name : "jack" }; }); */ /* 同一份文件不能同時存在多個define */ /* 不然後者的定義會覆蓋前者 */ // define({interest:"games"});
temp模塊數組
define("halo, My name is {{name}}");
async模塊
異步
define(function(require, exports, module) { console.log("異步加載的模塊!因此你最後才能看到我"); });
hello模塊,這裏主要是非標準模式下定義模塊注意
async
一、id和deps的細節,開始在這裏繞了一下,若是module.id與module.uri不一致會致使其餘模塊加載失敗函數
二、deps數組定義了依賴的模塊並接管require(path)路徑加載模塊方式,若是不在這裏聲明,模塊內部是不能經過路徑和別名成功加載其餘依賴模塊
更詳細說明看 https://github.com/seajs/seajs/issues/930
/* id 和 dependencies 參數能夠省略。省略時,能夠經過構建工具自動生成。 */ /* 帶 id 和 deps 參數的 define 用法不屬於 CMD 規範,而屬於 Modules/Transport 規範 */ /* https://github.com/seajs/seajs/issues/930 在這裏可以更好理解ID做用 */ define('../static/hello', ['jquery'], function(require, exports, module) { /* 當使用這種id和deps的方式時,dependencies會接管全部模塊依賴 */ /* 因此下面這種按照以往加載其餘模塊將會失敗,返回null */ var o = require('./other'); console.log(o);//null /* 在deps中聲明加載,因此可以正確獲取jq對象 */ var j = require('jquery'); console.log(j); exports.halo = function() { return "halo my friends"; }; });
other模塊
define({ name : "other module", varsion : "1.0.1" });
最終執行結果,在firefox的控制檯下