]> BookStack Code Mirror - bookstack/blob - resources/js/services/events.js
Added code editor changes mobile design handling
[bookstack] / resources / js / services / events.js
1 const listeners = {};
2 const stack = [];
3
4 /**
5  * Emit a custom event for any handlers to pick-up.
6  * @param {String} eventName
7  * @param {*} eventData
8  */
9 function emit(eventName, eventData) {
10     stack.push({name: eventName, data: eventData});
11     if (typeof listeners[eventName] === 'undefined') return this;
12     let eventsToStart = listeners[eventName];
13     for (let i = 0; i < eventsToStart.length; i++) {
14         let event = eventsToStart[i];
15         event(eventData);
16     }
17 }
18
19 /**
20  * Listen to a custom event and run the given callback when that event occurs.
21  * @param {String} eventName
22  * @param {Function} callback
23  * @returns {Events}
24  */
25 function listen(eventName, callback) {
26     if (typeof listeners[eventName] === 'undefined') listeners[eventName] = [];
27     listeners[eventName].push(callback);
28 }
29
30 /**
31  * Emit an event for public use.
32  * Sends the event via the native DOM event handling system.
33  * @param {Element} targetElement
34  * @param {String} eventName
35  * @param {Object} eventData
36  */
37 function emitPublic(targetElement, eventName, eventData) {
38     const event = new CustomEvent(eventName, {
39         detail: eventData,
40         bubbles: true
41     });
42     targetElement.dispatchEvent(event);
43 }
44
45 /**
46  * Notify of a http error.
47  * Check for standard scenarios such as validation errors and
48  * formats an error notification accordingly.
49  * @param {Error} error
50  */
51 function showValidationErrors(error) {
52     if (!error.status) return;
53     if (error.status === 422 && error.data) {
54         const message = Object.values(error.data).flat().join('\n');
55         emit('error', message);
56     }
57 }
58
59 export default {
60     emit,
61     emitPublic,
62     listen,
63     success: (msg) => emit('success', msg),
64     error: (msg) => emit('error', msg),
65     showValidationErrors,
66 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.