阅读前需要具备js基础(this,js原型链,继承,立即执行函数等)
关键点:
1.通过立即执行函数,来达到隐藏细节的目的
2.防止污染全局变量
3.代码解耦,提高复用性
下面是三个我总结的组件例子
- 原生js版:
var myModule = (function(){
function _myModule(ct){
this.ct = ct;
this.init(); //初始化
this.render(); //渲染
this.bind(); //绑定事件
}
_myModule.prototype = { //定义原型方法
init: function(){
this.var1 = 1;
this.var2 = 2;
},
render: function(){
xxx
},
bind: function(){
xxx
},
fn1: function(){
xxxxxx
},
fn2: function(){
xxxxxx
}
}
return {
init: function(cts){
cts.forEach(function(ct){
new _myModule(ct)
});
}
}
})();
//假设页面有多个div.box
myModule.init(document.querySelectorAll('.box'))
2.jQuery版:
var myModule = (function(){
function _myModule(ct){
this.ct = ct;
this.init(); //初始化
this.render(); //渲染
this.bind(); //绑定事件
}
_myModule.prototype = { //定义原型方法
init: function(){
this.var1 = 1;
this.var2 = 2;
},
render: function(){
xxx
},
bind: function(){
xxx
},
fn1: function(){
xxxxxx
},
fn2: function(){
xxxxxx
}
}
return {
init: function($ct){
$ct.each(function(index, ct){
new _myModule($(ct));
});
}
}
})();
//假设页面有多个div.box
myModule.init($('.box'));
3.jQuery插件版:
var myModule = (function(){
function MyModule(ct){
this.ct = ct;
this.init(); //初始化
this.render(); //渲染
this.bind(); //绑定事件
}
MyModule.prototype = { //定义原型方法
init: function(){
this.var1 = 1;
this.var2 = 2;
},
render: function(){
xxx
},
bind: function(){
xxx
},
fn1: function(){
xxxxxx
},
fn2: function(){
xxxxxx
}
}
return {
//给jQuery对象添加方法
init: $.fn.MyModule = function(){
this.each(function(){
new myModule($(this));
});
}
}
})();
//假设页面有多个div.box
$(".box").MyModule();
理解上面三个例子后,
可以做几个实例或者尝试把自己以前做的功能组件化。
附带几个我做的组件化demo,demo中可以看到两个组件互不干扰:
1.轮播组件
点击查看源码
2.懒加载(曝光)组件
点击查看源码
3.Tab组件
点击查看源码
4.日历组件
点击查看源码
5.modal组件
点击查看源码