UNPKG

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