UNPKG

2.28 kBJavaScriptView Raw
1"use strict";
2
3exports.__esModule = true;
4exports.on = on;
5exports.once = once;
6/**
7 * 取消事件绑定
8 * @param {*} node DOM节点或任何可以绑定事件的对象
9 * @param {String} eventName 事件名
10 * @param {Function} callback 回调方法
11 * @param {Boolean} [useCapture=false] 是否开启事件捕获优先
12 */
13function _off(node, eventName, callback, useCapture) {
14 /* istanbul ignore else */
15 if (node.removeEventListener) {
16 node.removeEventListener(eventName, callback, useCapture || false);
17 }
18}
19
20/**
21 * 绑定事件
22 * @param {*} node DOM节点或任何可以绑定事件的对象
23 * @param {String} eventName 事件名
24 * @param {Function} callback 回调方法
25 * @param {Boolean} useCapture 是否开启事件捕获优先
26 * @return {Object} 返回的object中包含一个off方法,用于取消事件监听
27 *
28 * @example
29 * const handler = events.on(document.body, 'click', e => {
30 * // handle click ...
31 * });
32 * // 取消事件绑定
33 * handler.off();
34 */
35exports.off = _off;
36function on(node, eventName, callback, useCapture) {
37 /* istanbul ignore else */
38 if (node.addEventListener) {
39 node.addEventListener(eventName, callback, useCapture || false);
40 }
41
42 return {
43 off: function off() {
44 return _off(node, eventName, callback, useCapture);
45 }
46 };
47}
48
49/**
50 * 绑定事件,只执行一次后销毁
51 * @param {*} node DOM节点或任何可以绑定事件的对象
52 * @param {String} eventName 事件名
53 * @param {Function} callback 回调方法
54 * @param {Boolean} useCapture 是否开启事件捕获优先
55 * @return {Function} 返回的object中包含一个off方法,用于取消事件监听
56 */
57function once(node, eventName, callback, useCapture) {
58 return on(node, eventName, function __fn() {
59 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
60 args[_key] = arguments[_key];
61 }
62
63 callback.apply(this, args);
64
65 // 由于addEventListener中的参数options只在Chrome 55、Firefox(Gecko)以上版本支持,故还是用传统的方法实现once
66 _off(node, eventName, __fn, useCapture);
67 }, useCapture);
68}
\No newline at end of file