1 | /**
|
2 | * Copyright (c) 2017, Philip Walton <philip@philipwalton.com>
|
3 | */
|
4 |
|
5 | /**
|
6 | * Dispatches an event on the passed element.
|
7 | * @param {!Element} element The DOM element to dispatch the event on.
|
8 | * @param {string} eventType The type of event to dispatch.
|
9 | * @param {Object|string=} eventName A string name of the event constructor
|
10 | * to use. Defaults to 'Event' if nothing is passed or 'CustomEvent' if
|
11 | * a value is set on `initDict.detail`. If eventName is given an object
|
12 | * it is assumed to be initDict and thus reassigned.
|
13 | * @param {Object=} initDict The initialization attributes for the
|
14 | * event. A `detail` property can be used here to pass custom data.
|
15 | * @return {boolean} The return value of `element.dispatchEvent`, which will
|
16 | * be false if any of the event listeners called `preventDefault`.
|
17 | */
|
18 | export function dispatch(
|
19 | element,
|
20 | eventType,
|
21 | evtName = 'Event',
|
22 | init_dict = {}
|
23 | ) {
|
24 | let event;
|
25 | let isCustom;
|
26 | let initDict = init_dict;
|
27 | let eventName = evtName;
|
28 |
|
29 | // eventName is optional
|
30 | if (typeof eventName === 'object') {
|
31 | initDict = eventName;
|
32 | eventName = 'Event';
|
33 | }
|
34 |
|
35 | initDict['bubbles'] = initDict['bubbles'] || false;
|
36 | initDict['cancelable'] = initDict['cancelable'] || false;
|
37 | initDict['composed'] = initDict['composed'] || false;
|
38 |
|
39 | // If a detail property is passed, this is a custom event.
|
40 | if ('detail' in initDict) isCustom = true;
|
41 | eventName = isCustom ? 'CustomEvent' : eventName;
|
42 |
|
43 | // Tries to create the event using constructors, if that doesn't work,
|
44 | // fallback to `document.createEvent()`.
|
45 | try {
|
46 | event = new window[eventName](eventType, initDict);
|
47 | } catch (err) {
|
48 | event = document.createEvent(eventName);
|
49 | const initMethod = 'init' + (isCustom ? 'Custom' : '') + 'Event';
|
50 | event[initMethod](
|
51 | eventType,
|
52 | initDict['bubbles'],
|
53 | initDict['cancelable'],
|
54 | initDict['detail']
|
55 | );
|
56 | }
|
57 |
|
58 | return element.dispatchEvent(event);
|
59 | }
|