[d565449] | 1 | "use strict";
|
---|
| 2 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
| 3 | var react_1 = require("react");
|
---|
| 4 | var util_1 = require("./misc/util");
|
---|
| 5 | var defaultTarget = util_1.isBrowser ? window : null;
|
---|
| 6 | var isListenerType1 = function (target) {
|
---|
| 7 | return !!target.addEventListener;
|
---|
| 8 | };
|
---|
| 9 | var isListenerType2 = function (target) {
|
---|
| 10 | return !!target.on;
|
---|
| 11 | };
|
---|
| 12 | var useEvent = function (name, handler, target, options) {
|
---|
| 13 | if (target === void 0) { target = defaultTarget; }
|
---|
| 14 | react_1.useEffect(function () {
|
---|
| 15 | if (!handler) {
|
---|
| 16 | return;
|
---|
| 17 | }
|
---|
| 18 | if (!target) {
|
---|
| 19 | return;
|
---|
| 20 | }
|
---|
| 21 | if (isListenerType1(target)) {
|
---|
| 22 | util_1.on(target, name, handler, options);
|
---|
| 23 | }
|
---|
| 24 | else if (isListenerType2(target)) {
|
---|
| 25 | target.on(name, handler, options);
|
---|
| 26 | }
|
---|
| 27 | return function () {
|
---|
| 28 | if (isListenerType1(target)) {
|
---|
| 29 | util_1.off(target, name, handler, options);
|
---|
| 30 | }
|
---|
| 31 | else if (isListenerType2(target)) {
|
---|
| 32 | target.off(name, handler, options);
|
---|
| 33 | }
|
---|
| 34 | };
|
---|
| 35 | }, [name, handler, target, JSON.stringify(options)]);
|
---|
| 36 | };
|
---|
| 37 | exports.default = useEvent;
|
---|