模块化JS编程 seajs简单例子

 

1.引入sea.js

test.html

 

 1 <!doctype html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <title>My Frist SeaJs</title>
 6 </head>
 7 <body>
 8 <div id="container">
 9  
10 </div>
11 
12 <script src="../sea-modules/seajs/seajs/2.2.0/sea.js"></script>
13 <script>
14 
15   // Set configuration
16     seajs.config({
17          alias: {
18              "jquery": "../script/jquery-1.11.1"
19         }
20     });
21 
22   seajs.use("../script/mysea.js");
23 </script>
24 
25 </body>
26 </html>

 

2.定义mysea.js

mysea.js

 

1 define(function (require, exports, module) {
//获得依赖
2 var mysea2 = require('../script/mysea2'); 3 mysea2.show(); 4 });

 

2.定义mysea2.js

mysea2.js

 

1 define(function (require, exports, module) {
//暴露show接口
2 exports.show = function() { 3 alert('mysea2'); 4 }; 5 });

 

输出结果:

 

 

模块化编程的目的很明显,我们不在像以前那样function(),function()的编写代码.我们可以很自由的组织代码,可避免一些代码冲突.

这里有个小问题,demo 引用的是jquery-1.11.1.由于jquery遵循是AMD规范. 在seajs官网的例子运行是没有问题的,因为作了修改(seajs是CMD规范).

所以jquery-1.11.1也做了修改,否则依赖的jquery会找不到的.

 

jquery-1.11原本的定义

1 if (typeof define === "function" && define.amd) {
2         define("jquery", [], function () {
3         return jQuery;
4    });
5 }

 

修改如下

1 if (typeof define === "function") {
//合理的路径
2 define("../script/jquery-1.11.1", [], function () { return jQuery; }); 3 }

 

关于规范

AMD规范:https://github.com/amdjs/amdjs-api/wiki/AMD

seajs模块定义规范:https://github.com/seajs/seajs/issues/242

 

 

下载seajs
 

 
posted @ 2014-07-19 17:47  chenchangwen  阅读(433)  评论(0编辑  收藏  举报