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 369 : export function event_mixin(obj, handlers) {
11 369 : Object.defineProperties(obj, {
12 369 : addEventListener: {
13 369 : enumerable: false,
14 369 : value: function addEventListener(type, handler) {
15 369 : if (handlers[type] === undefined)
16 369 : handlers[type] = [];
17 369 : handlers[type].push(handler);
18 369 : }
19 369 : },
20 369 : removeEventListener: {
21 369 : enumerable: false,
22 386 : value: function removeEventListener(type, handler) {
23 352 : const length = handlers[type] ? handlers[type].length : 0;
24 386 : for (let i = 0; i < length; i++) {
25 386 : if (handlers[type][i] === handler) {
26 386 : handlers[type][i] = null;
27 386 : break;
28 386 : }
29 386 : }
30 386 : }
31 369 : },
32 369 : dispatchEvent: {
33 369 : enumerable: false,
34 400 : value: function dispatchEvent(event) {
35 400 : let type, args;
36 400 : if (typeof event === "string") {
37 400 : type = event;
38 400 : args = Array.prototype.slice.call(arguments, 1);
39 :
40 400 : let detail = null;
41 400 : if (arguments.length == 2)
42 400 : detail = arguments[1];
43 400 : else if (arguments.length > 2)
44 392 : detail = args;
45 :
46 400 : event = new CustomEvent(type, {
47 400 : bubbles: false,
48 400 : cancelable: false,
49 400 : detail
50 400 : });
51 :
52 400 : args.unshift(event);
53 98 : } else {
54 98 : type = event.type;
55 98 : args = arguments;
56 98 : }
57 400 : if (is_function(obj['on' + type]))
58 98 : obj['on' + type].apply(obj, args);
59 400 : invoke_functions(handlers[type], obj, args);
60 400 : }
61 369 : }
62 369 : });
63 369 : }
|