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