@appius-fr/apx 2.5.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,235 @@
1
+ # APX Listen Module
2
+
3
+ The `listen` module provides a powerful event handling system for APX objects. It enables event delegation, multiple callback chaining, debouncing via timeouts, and manual event triggering.
4
+
5
+ ---
6
+
7
+ ## Installation
8
+
9
+ The `listen` module is automatically included when you import APX. It augments all APX objects with the `.listen()` and `.trigger()` methods.
10
+
11
+ ```javascript
12
+ import APX from './APX.mjs';
13
+ // .listen() and .trigger() are now available on all APX objects
14
+ ```
15
+
16
+ ---
17
+
18
+ ## Usage
19
+
20
+ ### Basic Event Listening
21
+
22
+ ```javascript
23
+ // Listen to a single event type
24
+ APX('.my-button').listen('click').do((event) => {
25
+ console.log('Button clicked!', event.target);
26
+ });
27
+
28
+ // Listen to multiple event types
29
+ APX('.my-input').listen(['input', 'change']).do((event) => {
30
+ console.log('Input changed:', event.target.value);
31
+ });
32
+ ```
33
+
34
+ ### Event Delegation
35
+
36
+ Use event delegation to handle events on dynamically added elements:
37
+
38
+ ```javascript
39
+ // Listen for clicks on any button inside the container (even if added later)
40
+ APX('#container').listen('click', '.button').do((event) => {
41
+ console.log('Button clicked:', event.target);
42
+ });
43
+ ```
44
+
45
+ ### Multiple Callbacks (Chaining)
46
+
47
+ Chain multiple callbacks that execute sequentially:
48
+
49
+ ```javascript
50
+ APX('.my-button').listen('click').do((event) => {
51
+ console.log('First callback');
52
+ return fetch('/api/data'); // Can return promises
53
+ }).do((event) => {
54
+ console.log('Second callback (runs after first completes)');
55
+ }).do((event) => {
56
+ console.log('Third callback');
57
+ });
58
+ ```
59
+
60
+ ### Debouncing with Timeout
61
+
62
+ Add a delay before executing callbacks:
63
+
64
+ ```javascript
65
+ // Wait 300ms after the last event before executing callbacks
66
+ APX('.search-input').listen('input', { timeout: 300 }).do((event) => {
67
+ console.log('Searching for:', event.target.value);
68
+ // This will only fire 300ms after the user stops typing
69
+ });
70
+ ```
71
+
72
+ ### Manual Event Triggering
73
+
74
+ Manually trigger events and their registered callbacks:
75
+
76
+ ```javascript
77
+ // Trigger a click event
78
+ APX('.my-button').trigger('click');
79
+
80
+ // Or trigger with an actual Event object
81
+ const customEvent = new CustomEvent('myevent', { detail: { data: 'value' } });
82
+ APX('.my-element').trigger(customEvent);
83
+ ```
84
+
85
+ ---
86
+
87
+ ## API
88
+
89
+ ### `.listen(eventTypes, selector?, options?)`
90
+
91
+ Adds event listeners to the APX-wrapped elements.
92
+
93
+ **Parameters:**
94
+ - `eventTypes` (string | string[]): The event type(s) to listen for (e.g., `'click'`, `['input', 'change']`)
95
+ - `selector` (string, optional): CSS selector for event delegation
96
+ - `options` (object, optional): Configuration options
97
+ - `timeout` (number): Delay in milliseconds before executing callbacks (default: `0`)
98
+
99
+ **Returns:** An object with a `.do()` method for chaining callbacks.
100
+
101
+ **Example:**
102
+ ```javascript
103
+ APX('.element')
104
+ .listen('click', '.button', { timeout: 100 })
105
+ .do((event) => { /* callback 1 */ })
106
+ .do((event) => { /* callback 2 */ });
107
+ ```
108
+
109
+ ### `.do(callback)`
110
+
111
+ Adds a callback function to the event listener chain. Callbacks execute sequentially, and each callback can return a Promise to delay the next callback.
112
+
113
+ **Parameters:**
114
+ - `callback` (Function): The callback function that receives the event object
115
+
116
+ **Returns:** The same object (for chaining)
117
+
118
+ **Example:**
119
+ ```javascript
120
+ APX('.button').listen('click').do((event) => {
121
+ // Callback is bound to the matched element
122
+ console.log(this); // The matched element
123
+ return fetch('/api').then(res => res.json());
124
+ }).do((event) => {
125
+ // This runs after the fetch completes
126
+ console.log('Fetch completed');
127
+ });
128
+ ```
129
+
130
+ ### `.trigger(event)`
131
+
132
+ Manually triggers an event on all wrapped elements and executes registered callbacks.
133
+
134
+ **Parameters:**
135
+ - `event` (string | Event): Event type string or an Event object
136
+
137
+ **Example:**
138
+ ```javascript
139
+ // Trigger with string
140
+ APX('.button').trigger('click');
141
+
142
+ // Trigger with Event object
143
+ const event = new CustomEvent('custom', { detail: { foo: 'bar' } });
144
+ APX('.element').trigger(event);
145
+ ```
146
+
147
+ ---
148
+
149
+ ## Examples
150
+
151
+ ### Form Validation with Debouncing
152
+
153
+ ```javascript
154
+ APX('#email-input').listen('input', { timeout: 500 }).do((event) => {
155
+ const email = event.target.value;
156
+ if (email.includes('@')) {
157
+ validateEmail(email);
158
+ }
159
+ });
160
+ ```
161
+
162
+ ### Dynamic Content with Event Delegation
163
+
164
+ ```javascript
165
+ // Handle clicks on buttons added dynamically
166
+ APX('#dynamic-container').listen('click', '.action-button').do((event) => {
167
+ const button = event.target;
168
+ const action = button.dataset.action;
169
+ handleAction(action);
170
+ });
171
+ ```
172
+
173
+ ### Sequential Async Operations
174
+
175
+ ```javascript
176
+ APX('#submit-button').listen('click').do(async (event) => {
177
+ // First: Validate form
178
+ const isValid = await validateForm();
179
+ if (!isValid) throw new Error('Validation failed');
180
+ }).do(async (event) => {
181
+ // Second: Submit form (only if validation passed)
182
+ const result = await submitForm();
183
+ return result;
184
+ }).do((event) => {
185
+ // Third: Show success message
186
+ showSuccessMessage();
187
+ });
188
+ ```
189
+
190
+ ### Multiple Event Types
191
+
192
+ ```javascript
193
+ APX('.input-field').listen(['focus', 'blur', 'input']).do((event) => {
194
+ switch (event.type) {
195
+ case 'focus':
196
+ highlightField(event.target);
197
+ break;
198
+ case 'blur':
199
+ validateField(event.target);
200
+ break;
201
+ case 'input':
202
+ updatePreview(event.target.value);
203
+ break;
204
+ }
205
+ });
206
+ ```
207
+
208
+ ---
209
+
210
+ ## Features
211
+
212
+ - ✅ **Event Delegation**: Handle events on dynamically added elements
213
+ - ✅ **Multiple Callbacks**: Chain multiple callbacks that execute sequentially
214
+ - ✅ **Promise Support**: Callbacks can return Promises for async operations
215
+ - ✅ **Debouncing**: Add timeouts to delay callback execution
216
+ - ✅ **Multiple Event Types**: Listen to multiple event types at once
217
+ - ✅ **Manual Triggering**: Programmatically trigger events and callbacks
218
+ - ✅ **Context Binding**: Callbacks are bound to the matched element (`this`)
219
+
220
+ ---
221
+
222
+ ## Notes
223
+
224
+ - Callbacks execute sequentially; if a callback returns a Promise, the next callback waits for it to resolve
225
+ - Event delegation uses `closest()` to find the matching element, so it works with nested elements
226
+ - Timeouts are cleared and reset on each event, making it perfect for debouncing
227
+ - The `trigger()` method respects event delegation selectors when executing callbacks
228
+
229
+ ---
230
+
231
+ ## License
232
+
233
+ Author : Thibault SAELEN
234
+ Copyright Appius SARL.
235
+