]> BookStack Code Mirror - bookstack/blob - resources/js/services/events.js
Added content-perms API examples and docs tweaks
[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 standard server-provided validation errors.
47  * @param {Object} error
48  */
49 function showValidationErrors(error) {
50     if (!error.status) return;
51     if (error.status === 422 && error.data) {
52         const message = Object.values(error.data).flat().join('\n');
53         emit('error', message);
54     }
55 }
56
57 /**
58  * Notify standard server-provided error messages.
59  * @param {Object} error
60  */
61 function showResponseError(error) {
62     if (!error.status) return;
63     if (error.status >= 400 && error.data && error.data.message) {
64         emit('error', error.data.message);
65     }
66 }
67
68 export default {
69     emit,
70     emitPublic,
71     listen,
72     success: (msg) => emit('success', msg),
73     error: (msg) => emit('error', msg),
74     showValidationErrors,
75     showResponseError,
76 }