可参考的requirejs学习资源:
https://www.haorooms.com/post/requirejs_sy_lj
js 不是一门严格面向对象的开发工具,require.js提供了实现js 模块化开发的方法,避免了对象作用域污染;
一、引入require.js文件
<script src="scripts/require.js" data-main="scripts/app.js"></script>
其中data-main导入了主模块;
二、require配置
require配置的主要作用是加载模块根路径,映射非根路径,同时加载非require模块的脚本。
require.config() 配置
通过这个函数可以对requirejs进行灵活的配置,其参数为一个配置对象,配置项及含义如下:
baseUrl——用于加载模块的根路径。
paths——用于映射不存在根路径下面的模块路径。
shims——配置在脚本/模块外面并没有使用RequireJS的函数依赖并且初始化函数。假设underscore并没有使用 RequireJS定义,但是你还是想通过RequireJS来使用它,那么你就需要在配置中把它定义为一个shim。
require.config({
//默认情况下从这个文件开始拉去取资源
baseUrl:'scripts/app',
//如果你的依赖模块以pb头,会从scripts/pb加载模块。
paths:{
pb:'../pb'
},
// load backbone as a shim,所谓就是将没有采用requirejs方式定义
//模块的东西转变为requirejs模块,exports表示导出的模块,而deps为依赖的模块
//============hello中存在两个以上对象时,不能采用exports导出对象,需要使用init函数,返回多个对象
shim:{
'backbone':{
deps:['underscore'],
exports:'Backbone'
},
hello: {
init: function() {
return {
hello: hello,
hello2: hello2
}
}
}
}
});
三、定义模块
使用define函数定义模块,define函数接受两个参数。
* 第一个是一个字符串数组,表示你定义的模块依赖的模块,可依赖多个模块;
* 第二个参数是一个回调函数,当依赖模块加载成功后,被调用:参数是注入前面依赖的模块,顺序同第一参数顺序,即传入依赖模块并将其依次命名为相应的对象。在函数中可做逻辑处理,通过return一个对象暴露模块的属性和方法,不在return中的可以认为是私有方法和私有属性,只有return返回的方法和属性才能在其它模块 中被引用。
//====当前定义的模块依赖于模块a,将模块a中返回的对象命名为a,传入当前模块=============
define(["a"], function(a) {
'use strict';
function info() {
console.log("我是私有函数");
}
return {
name:"一个属性",
test:function(a){
console.log(a+"你好!");
a.f();
info();
}
}
});
也可通过如下方式定义模块,其中require,均为外部传入的模块命名对象
define(function(require,$){
var data={text:""};
var obj=new Object({
c1:10,
text: function (str) {
data.text=str;
},
doEach:function(){
alert(data.text);
},
doNext:function(){
alert(this.text);
}
});
//==========num 相当于是匿名函数function()的返回结果================
var num=(function(){
var m1=function(a,b){
return a+b;
}
var m2=function(a,b){
return a-b;
}
//===========返回一个对象======================
return {m1:m1,m2:m2};
})();
//obj.c2=1000;
var objTmp={c2:1000,showC2:function(){
obj.c2=obj.c2+1000;
alert(obj.c2);
}};
obj=$.extend(obj,objTmp);
var obj1=(function(mod){
mod.showString=function()
{
alert("this is a string");
}
return mod;
//===========下面的obj相当于是function(mod)的传入参数=====================
})(obj);
return {
obj:obj,
num:num,
data:data
}
}(require,$));
四、应用模块
使用require函数加载已定义的模块,示例代码如下:
//=============命名全局对象app==========================
var app;
//=============导入jquery模块,命名为对象$============================
require(["jquery"],function($){
console.log("the jquery load succes!");
//=============导入app目录下的app模块文件,将其命名为app1变量===========
require(["app/app"],function(app1){
function setClickEvent(btnName)
{
app.obj.text(btnName);
//===========好像在jquery中不能向一般为document 添加元素事件 事件==事件函数的方式增加事件响应,而是事件(事件响应函数);===切记切记
$(btnName).click(app.obj.doEach);
$(btnName).text(btnName);
}
//======回调函数中的参数app就是创建的模块对象本身=======
var tmp={
sex:"male",
old:34
};
//=============赋值全局对象====================
app=$.extend(app1,tmp);
//=============执行全局对象方法==================
app.obj.doEach();
//===============增加ready事件相应函数=================================
$(document).ready(function(){
//===============直接应用同一模块中的方法======================
setClickEvent("#btn1");
setClickEvent("#btn2");
setClickEvent("#btn3");
});
/*require(["app/addEvent"],function(event){
console.log("event add");
});*/
});
});
require()函数接受两个参数。第一个参数是一个数组,表示所依赖的模块;第二个参数是一个回调函数,当前面指定的模块都加载成功后,它才会被调用。
五、完整例子
js目录结构如下:
html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="js/require.js" data-main="app.js"></script>
</body>
</html>
主模块js:
require.config({
//By default load any module IDs from js/
baseUrl: 'js',
//except, if the module ID starts with "pb"
paths: {
pb: '../pb'
},
shim: {
'world': {
deps:['animalWorld'],
// use the global 'Backbone' as the module name.
exports: 'world'
}
}
});
require(['cat','dog','world'], function (cat,dog,world) {
world.world();
cat.say();
dog.say();
});
animial.js
define([], function() {
'use strict';
function _showName(name){
console.log(name);
}
return {
say(words){
console.log(words);
},
showName(name){ //练习私有方法
_showName(name);
}
}
});
cat.js:
define([
'animal'
], function(animal) {
'use strict';
return {
say(){
animal.say("喵喵");
animal.showName("猫");
}
}
});
dog.js
define([
'animal'
], function(animal) {
'use strict';
return {
say(){
animal.say("汪汪");
animal.showName("狗");
}
}
});
欲更多的了解requie.js可以查阅: https://www.runoob.com/w3cnote/requirejs-tutorial-1.html,和获取更多信息