addEventListener与handleEvent

来源:互联网 发布:前端整么添加数据 编辑:程序博客网 时间:2024/05/29 10:36

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>
原创粉丝点击