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