1 . addEventListener方法用于给指定元素添加事件监听器
// 第二个参数function是指定要事件触发时执行的函数
element.addEventListener(event, function, useCapture)
2 . handleEvent 是实现Eventlistener的一种方式,如下
<script>
(function () {
// 作为一个工具类出现
var utils = {};
// 添加事件方法
utils.addEvent = function (type, el, fn, capture) {
// 注册事件监听器,capture = true 事件句柄在捕获阶段执行,也就是立即执行
el.addEventListener(type, fn, !!capture);
};
// 删除事件
utils.removeEvent = function (el, type, fn, capture) {
el.removeEventListener(type, fn, !!capture);
};
function Slidebar () {
this.sidebar = document.querySelector('.sidebar')
this.initEvent()
}
Slidebar.prototype = {
// 初始化事件
initEvent: function () {
utils.addEvent('touchstart', this.sidebar, this)
},
// 自动从传入的对象中寻找handleEvent方法
handleEvent: function (e) {
// 事件类型
console.log(e.type)
// 根据事件类型,定义不同的处理函数
switch ( e.type ) {
case 'touchstart':
this._start(e);
break;
}
},
// touchstart事件处理函数
_start: function (e) {
}
}
// 实例化
new Slidebar()
})()
</script>