Line data Source code
1 : // SPDX-License-Identifier: LGPL-2.1-or-later
2 : import { is_function, invoke_functions } from './common';
3 :
4 : /*
5 : * Extends an object to have the standard DOM style addEventListener
6 : * removeEventListener and dispatchEvent methods. The dispatchEvent
7 : * method has the additional capability to create a new event from a type
8 : * string and arguments.
9 : */
10 127 : export function event_mixin(obj, handlers) {
11 127 : Object.defineProperties(obj, {
12 127 : addEventListener: {
13 127 : enumerable: false,
14 127 : value: function addEventListener(type, handler) {
15 127 : if (handlers[type] === undefined)
16 127 : handlers[type] = [];
17 127 : handlers[type].push(handler);
18 127 : }
19 127 : },
20 127 : removeEventListener: {
21 127 : enumerable: false,
22 135 : value: function removeEventListener(type, handler) {
23 129 : const length = handlers[type] ? handlers[type].length : 0;
24 135 : for (let i = 0; i < length; i++) {
25 135 : if (handlers[type][i] === handler) {
26 135 : handlers[type][i] = null;
27 135 : break;
28 135 : }
29 135 : }
30 135 : }
31 127 : },
32 127 : dispatchEvent: {
33 127 : enumerable: false,
34 138 : value: function dispatchEvent(event) {
35 138 : let type, args;
36 138 : if (typeof event === "string") {
37 138 : type = event;
38 138 : args = Array.prototype.slice.call(arguments, 1);
39 :
40 138 : let detail = null;
41 138 : if (arguments.length == 2)
42 138 : detail = arguments[1];
43 138 : else if (arguments.length > 2)
44 134 : detail = args;
45 :
46 138 : event = new CustomEvent(type, {
47 138 : bubbles: false,
48 138 : cancelable: false,
49 138 : detail
50 138 : });
51 :
52 138 : args.unshift(event);
53 30 : } else {
54 30 : type = event.type;
55 30 : args = arguments;
56 30 : }
57 138 : if (is_function(obj['on' + type]))
58 30 : obj['on' + type].apply(obj, args);
59 138 : invoke_functions(handlers[type], obj, args);
60 138 : }
61 127 : }
62 127 : });
63 127 : }
|