您的位置:首页 > Web前端 > JavaScript

sea.js最佳实践一基础框架搭建

2014-06-16 14:37 423 查看
(一下代码都是基于sea.js vesion 2.0)

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
>
上面的data-config是指sea.js的配置文件的路径。还有一个属性是data-main,它项目的起始模块。data-main是可选项,我们这里不使用他。

首先我们来看看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
});
plugins选项配置插件,这里使用了shim插件,更多插件可点这里。由于jquery不是一个标准的CMD模块,所以直接加载jquery是错误的。这里使用了shim插件,会自动把jquery转换一成一个标准的CMD模块。不用人工改动jquery原码。alias是配置别名,方便加载的。同时它还有很多功能,比如加载依赖包等,这个后面会提到。

再看下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
});
上面我们加载了jquery,定义了一个模块加载函数。现在我们在html页面加入如下代码:

1
<script
type=
"text/javascript"
>
2
seajs.use(
'modules/app'
,
function
(app)
{
3
app.script_load(
'index'
);
4
});
5
</script>
这样就会去加载index模块,并执行index模块里的exports.run方法。

index.js

1
define(
function
(require,
exports,module) {
2
exports.run
=
function
()
{
3
$(
'#alert'
).click(
function
()
{
4
alert(
'弹出了一个框!'
);
5
});
6
}
7
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: