Requirejs是非常小巧的模块载入框架,很好的实现AMD思想。今天初探requirejs,下面写个小demo。
首先 栗子 放在一个目录下,其下有个js文件夹目录:
|-index.js
|-js
|-init.js
|-1.js
|-2.js
|-3.j
index.html:在页面script标签引入requirejs,通过data-main指定网页程序的主模块。
<script src="js/require.js" data-main="js/init.js"></script>
init.js 此文件为网页程序的主模块,引入模块方法有两种方式如下:(建议使用方法一)
方法一:
require(function(require){
var mod = require('3');
alert.(mod.a);
});
方法二:
require(['js/3'],function(mod){
alert(mod.a);
});
主模块中引入了3.js模块,其中3.js模块:
3.js:
define(function(require){
var mod1 = require('1')
return {
a:mod1,
b:2
}
});
3.js中引入了1.js模块,其中1.js模块:
1.js
define(function(){
alert(1);
return 3;
});
以上就是简单的requirejs定义引用模块方法!
下面来个稍微复杂一点的,就封装一个简单的自定义滚动条栗子做一个模块化:
同样在script标签中引入
index.html:
init.js
require(['index'])
index.js
define(['setT','addWheel'],function(setT,addWheel){
var oBox = document.getElementById('box');
var oLeft = document.getElementById('left');
var oCon = document.getElementById('content');
var oRight = document.getElementById('right');
var oBar = document.getElementById('bar');
oBar.onmousedown = function(ev) {
var oEvent = ev || event;
var disY = oEvent.clientY - oBar.offsetTop;
document.onmousemove = function(ev) {
var oEvent = ev || event;
var t = oEvent.clientY - disY;
setT(t);
};
document.onmouseup = function() {
document.onmousemove = null;
document.onmouseup = null;
oBar.releaseCapture && oBar.releaseCapture();
};
oBar.setCapture && oBar.setCapture();
return false;
};
//添加滚轮
addWheel(oBox,function(bDown) {
var iT = oBar.offsetTop;
if (bDown) {
iT += 10;
} else {
iT -= 10;
}
setT(iT);
});
})
setT.js
define(function(){var oBox = document.getElementById('box');
var oLeft = document.getElementById('left');
var oCon = document.getElementById('content');
var oRight = document.getElementById('right');
var oBar = document.getElementById('bar');
return function setT(t) {
var maxH = oRight.offsetHeight - oBar.offsetHeight;
t < 0 && (t = 0);
t > maxH && (t = maxH);
oBar.style.top = t + 'px';
var scale = t / maxH;
oCon.style.top = -scale*(oCon.offsetHeight-oLeft.offsetHeight) + 'px';
}
});
addWhell.js
define(['addEvent'],function(addEvent){
return function addWheel(obj,fn) {
function wheel(ev) {
var oEvent = ev || event;
var bDown = oEvent.wheelDelta ? oEvent.wheelDelta < 0 : oEvent.detail > 0;
fn && fn(bDown);
oEvent.preventDefault && oEvent.preventDefault();
return false;
}
// 判断浏览器类型
if (window.navigator.userAgent.indexOf('Firefox') != -1) {
// FF
obj.addEventListener('DOMMouseScroll',wheel,false);
} else {
// Chrome IE
addEvent(obj,'mousewheel',wheel);
}
}
});
addEvent.js
define(function(){
return function addEvent(obj,sEv,fn) {
if (obj.addEventListener) {
obj.addEventListener(sEv,fn,false);
} else {
obj.attachEvent('on'+sEv,fn);
}
}
});