sea.js最佳实践一基础框架搭建
2014-06-16 14:37
423 查看
(一下代码都是基于sea.js vesion 2.0)
上面的data-config是指sea.js的配置文件的路径。还有一个属性是data-main,它项目的起始模块。data-main是可选项,我们这里不使用他。
首先我们来看看sea-js-config.js
plugins选项配置插件,这里使用了shim插件,更多插件可点这里。由于jquery不是一个标准的CMD模块,所以直接加载jquery是错误的。这里使用了shim插件,会自动把jquery转换一成一个标准的CMD模块。不用人工改动jquery原码。alias是配置别名,方便加载的。同时它还有很多功能,比如加载依赖包等,这个后面会提到。
再看下app.js
上面我们加载了jquery,定义了一个模块加载函数。现在我们在html页面加入如下代码:
这样就会去加载index模块,并执行index模块里的exports.run方法。
index.js
01 | index.html |
02 | <!-- lang: html --> |
03 | < html > |
04 | < head > |
05 | < title >sea.js最佳实践</ title > |
06 | < style type = "text/css" > |
07 | #alert { |
08 | padding: 10px 20px; |
09 | background: green; |
10 | float: left; |
11 | color: #fff; |
12 | cursor: pointer; |
13 | } |
14 | </ style > |
15 | < script type = "text/javascript" src = "js/seajs/2.0.0/sea-debug.js?t=123" data-config = "sea-js-config.js?t=123" ></ script > |
16 | </ head > |
17 | < body > |
18 | < div id = "alert" >点击我</ div > |
19 | </ body > |
20 |
21 |
22 | </ html > |
首先我们来看看sea-js-config.js
01 | seajs.config({ |
02 | // 配置插件 |
03 | plugins: [ 'shim' ], |
04 |
05 | // 配置别名 |
06 | alias: { |
07 | // 配置 jquery 的 shim 配置,这样我们就可以通过 require('jquery') 来获取 jQuery |
08 | 'jquery' : { |
09 | src: 'libs/jquery/1.9.1/jquery.js' , //注意,这里是从sea.js所在目录的上两节目录开始查找文件 |
10 | exports: 'jQuery' |
11 | } |
12 | } |
13 | }); |
再看下app.js
01 | /** |
02 | *项目主模块 |
03 | */ |
04 | define( function (require, exports,module) { |
05 | //加载jquery, 并把它$设为全局变量 |
06 | window.$ = window.jQuery = $ = require( 'jquery' ); |
07 |
08 | //定义一个全局的模块加载函数.module为模块名,options为参数 |
09 | exports.script_load = function (module, options) { |
10 | //使用require.async异步加载模块。模块需要提供一个固定的对外调用接口,这里定义为run。 |
11 | require.async( 'modules/' + module, function (module) { |
12 | if ( typeof (module.run) === 'function' ) { |
13 | module.run(options); |
14 | } |
15 | }); |
16 | } |
17 |
18 | window.script_load = exports.script_load |
19 | }); |
1 | <script type= "text/javascript" > |
2 | seajs.use( 'modules/app' , function (app) { |
3 | app.script_load( 'index' ); |
4 | }); |
5 | </script> |
index.js
1 | define( function (require, exports,module) { |
2 | exports.run = function () { |
3 | $( '#alert' ).click( function () { |
4 | alert( '弹出了一个框!' ); |
5 | }); |
6 | } |
7 | }); |
相关文章推荐
- sea.js最佳实践一基础框架搭建
- 虚拟研讨会:Node.js生态系统之框架、库、最佳实践
- Yii框架官方指南系列15——基础知识:最佳MVC实践
- [转] 虚拟研讨会:Node.js生态系统之框架、库、最佳实践
- [Java框架-grails从基础到实践]7、集合
- [Java框架-grails从基础到实践]8、集合-map
- ORMapping 框架使用最佳实践
- 开发框架:Spring XML配置十二个最佳实践
- Spring 总结XML配置的十二个最佳实践-Java基础-Java-编程开发
- 基于C++的纯面向对象的通用高性能大并发TCP-SERVER/CLIENT开发框架实践系列之基础篇
- [Java框架-grails从基础到实践]6、循环
- Web 服务的最佳实践: 回到基础部分,第 1 部分
- 重温SSH小项目实践(1)--框架搭建篇
- 团队基础生成自动化流程之最佳实践(IV) - 重写团队基础默认生成流程
- 团队基础生成自动化流程之最佳实践(V) - 使用Desktop Build
- JQuery最佳实践-简单图片导航插件jquery.imgNav.js
- bboss 持久层框架使用最佳实践-带连接(connection)参数接口和不带连接参数接口的选择
- appfuse 2.0.1 Tapestry 在eclipse里调试环境的搭建(未验证是否为最佳实践)
- [Java框架-grails从基础到实践]1、grails简介
- 团队基础生成自动化流程之最佳实践总论(I) – 自动化生成流程基础