This repository has been archived by the owner on Nov 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
main.js
480 lines (420 loc) · 11.4 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
/**
* DOM event delegator
*
* The delegator will listen
* for events that bubble up
* to the root node.
*
* @constructor
* @param {Node|string} [root] The root node or a selector string matching the root node
*/
function Delegate(root) {
/**
* Maintain a map of listener
* lists, keyed by event name.
*
* @type Object
*/
this.listenerMap = [{}, {}];
if (root) {
this.root(root);
}
/** @type function() */
this.handle = Delegate.prototype.handle.bind(this);
// Cache of event listeners removed during an event cycle
this._removedListeners = [];
}
/**
* Start listening for events
* on the provided DOM element
*
* @param {Node|string} [root] The root node or a selector string matching the root node
* @returns {Delegate} This method is chainable
*/
Delegate.prototype.root = function (root) {
const listenerMap = this.listenerMap;
let eventType;
// Remove master event listeners
if (this.rootElement) {
for (eventType in listenerMap[1]) {
if (listenerMap[1].hasOwnProperty(eventType)) {
this.rootElement.removeEventListener(eventType, this.handle, true);
}
}
for (eventType in listenerMap[0]) {
if (listenerMap[0].hasOwnProperty(eventType)) {
this.rootElement.removeEventListener(eventType, this.handle, false);
}
}
}
// If no root or root is not
// a dom node, then remove internal
// root reference and exit here
if (!root || !root.addEventListener) {
if (this.rootElement) {
delete this.rootElement;
}
return this;
}
/**
* The root node at which
* listeners are attached.
*
* @type Node
*/
this.rootElement = root;
// Set up master event listeners
for (eventType in listenerMap[1]) {
if (listenerMap[1].hasOwnProperty(eventType)) {
this.rootElement.addEventListener(eventType, this.handle, true);
}
}
for (eventType in listenerMap[0]) {
if (listenerMap[0].hasOwnProperty(eventType)) {
this.rootElement.addEventListener(eventType, this.handle, false);
}
}
return this;
};
/**
* @param {string} eventType
* @returns boolean
*/
Delegate.prototype.captureForType = function (eventType) {
return ['blur', 'error', 'focus', 'load', 'resize', 'scroll'].indexOf(eventType) !== -1;
};
/**
* Attach a handler to one
* event for all elements
* that match the selector,
* now or in the future
*
* The handler function receives
* three arguments: the DOM event
* object, the node that matched
* the selector while the event
* was bubbling and a reference
* to itself. Within the handler,
* 'this' is equal to the second
* argument.
*
* The node that actually received
* the event can be accessed via
* 'event.target'.
*
* @param {string} eventType Listen for these events
* @param {string|undefined} selector Only handle events on elements matching this selector, if undefined match root element
* @param {function()} handler Handler function - event data passed here will be in event.data
* @param {boolean} [useCapture] see 'useCapture' in <https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener>
* @returns {Delegate} This method is chainable
*/
Delegate.prototype.on = function (eventType, selector, handler, useCapture) {
let root;
let listenerMap;
let matcher;
let matcherParam;
if (!eventType) {
throw new TypeError('Invalid event type: ' + eventType);
}
// handler can be passed as
// the second or third argument
if (typeof selector === 'function') {
useCapture = handler;
handler = selector;
selector = null;
}
// Fallback to sensible defaults
// if useCapture not set
if (useCapture === undefined) {
useCapture = this.captureForType(eventType);
}
if (typeof handler !== 'function') {
throw new TypeError('Handler must be a type of Function');
}
root = this.rootElement;
listenerMap = this.listenerMap[useCapture ? 1 : 0];
// Add master handler for type if not created yet
if (!listenerMap[eventType]) {
if (root) {
root.addEventListener(eventType, this.handle, useCapture);
}
listenerMap[eventType] = [];
}
if (!selector) {
matcherParam = null;
// COMPLEX - matchesRoot needs to have access to
// this.rootElement, so bind the function to this.
matcher = matchesRoot.bind(this);
// Compile a matcher for the given selector
} else if (/^[a-z]+$/i.test(selector)) {
matcherParam = selector;
matcher = matchesTag;
} else if (/^#[a-z0-9\-_]+$/i.test(selector)) {
matcherParam = selector.slice(1);
matcher = matchesId;
} else {
matcherParam = selector;
matcher = Element.prototype.matches;
}
// Add to the list of listeners
listenerMap[eventType].push({
selector: selector,
handler: handler,
matcher: matcher,
matcherParam: matcherParam
});
return this;
};
/**
* Remove an event handler
* for elements that match
* the selector, forever
*
* @param {string} [eventType] Remove handlers for events matching this type, considering the other parameters
* @param {string} [selector] If this parameter is omitted, only handlers which match the other two will be removed
* @param {function()} [handler] If this parameter is omitted, only handlers which match the previous two will be removed
* @returns {Delegate} This method is chainable
*/
Delegate.prototype.off = function (eventType, selector, handler, useCapture) {
let i;
let listener;
let listenerMap;
let listenerList;
let singleEventType;
// Handler can be passed as
// the second or third argument
if (typeof selector === 'function') {
useCapture = handler;
handler = selector;
selector = null;
}
// If useCapture not set, remove
// all event listeners
if (useCapture === undefined) {
this.off(eventType, selector, handler, true);
this.off(eventType, selector, handler, false);
return this;
}
listenerMap = this.listenerMap[useCapture ? 1 : 0];
if (!eventType) {
for (singleEventType in listenerMap) {
if (listenerMap.hasOwnProperty(singleEventType)) {
this.off(singleEventType, selector, handler);
}
}
return this;
}
listenerList = listenerMap[eventType];
if (!listenerList || !listenerList.length) {
return this;
}
// Remove only parameter matches
// if specified
for (i = listenerList.length - 1; i >= 0; i--) {
listener = listenerList[i];
if ((!selector || selector === listener.selector) && (!handler || handler === listener.handler)) {
this._removedListeners.push(listener);
listenerList.splice(i, 1);
}
}
// All listeners removed
if (!listenerList.length) {
delete listenerMap[eventType];
// Remove the main handler
if (this.rootElement) {
this.rootElement.removeEventListener(eventType, this.handle, useCapture);
}
}
return this;
};
/**
* Handle an arbitrary event.
*
* @param {Event} event
*/
Delegate.prototype.handle = function (event) {
let i;
let l;
const type = event.type;
let root;
let phase;
let listener;
let returned;
let listenerList = [];
let target;
const eventIgnore = 'ftLabsDelegateIgnore';
if (event[eventIgnore] === true) {
return;
}
target = event.target;
// Hardcode value of Node.TEXT_NODE
// as not defined in IE8
if (target.nodeType === 3) {
target = target.parentNode;
}
// Handle SVG <use> elements in IE
if (target.correspondingUseElement) {
target = target.correspondingUseElement;
}
root = this.rootElement;
phase = event.eventPhase || (event.target !== event.currentTarget ? 3 : 2);
// eslint-disable-next-line default-case
switch (phase) {
case 1: //Event.CAPTURING_PHASE:
listenerList = this.listenerMap[1][type];
break;
case 2: //Event.AT_TARGET:
if (this.listenerMap[0] && this.listenerMap[0][type]) {
listenerList = listenerList.concat(this.listenerMap[0][type]);
}
if (this.listenerMap[1] && this.listenerMap[1][type]) {
listenerList = listenerList.concat(this.listenerMap[1][type]);
}
break;
case 3: //Event.BUBBLING_PHASE:
listenerList = this.listenerMap[0][type];
break;
}
let toFire = [];
// Need to continuously check
// that the specific list is
// still populated in case one
// of the callbacks actually
// causes the list to be destroyed.
l = listenerList.length;
while (target && l) {
for (i = 0; i < l; i++) {
listener = listenerList[i];
// Bail from this loop if
// the length changed and
// no more listeners are
// defined between i and l.
if (!listener) {
break;
}
if (
target.tagName &&
["button", "input", "select", "textarea"].indexOf(target.tagName.toLowerCase()) > -1 &&
target.hasAttribute("disabled")
) {
// Remove things that have previously fired
toFire = [];
}
// Check for match and fire
// the event if there's one
//
// TODO:MCG:20120117: Need a way
// to check if event#stopImmediatePropagation
// was called. If so, break both loops.
else if (listener.matcher.call(target, listener.matcherParam, target)) {
toFire.push([event, target, listener]);
}
}
// TODO:MCG:20120117: Need a way to
// check if event#stopPropagation
// was called. If so, break looping
// through the DOM. Stop if the
// delegation root has been reached
if (target === root) {
break;
}
l = listenerList.length;
// Fall back to parentNode since SVG children have no parentElement in IE
target = target.parentElement || target.parentNode;
// Do not traverse up to document root when using parentNode, though
if (target instanceof HTMLDocument) {
break;
}
}
let ret;
for (i = 0; i < toFire.length; i++) {
// Has it been removed during while the event function was fired
if (this._removedListeners.indexOf(toFire[i][2]) > -1) {
continue;
}
returned = this.fire.apply(this, toFire[i]);
// Stop propagation to subsequent
// callbacks if the callback returned
// false
if (returned === false) {
toFire[i][0][eventIgnore] = true;
toFire[i][0].preventDefault();
ret = false;
break;
}
}
return ret;
};
/**
* Fire a listener on a target.
*
* @param {Event} event
* @param {Node} target
* @param {Object} listener
* @returns {boolean}
*/
Delegate.prototype.fire = function (event, target, listener) {
return listener.handler.call(target, event, target);
};
/**
* Check whether an element
* matches a tag selector.
*
* Tags are NOT case-sensitive,
* except in XML (and XML-based
* languages such as XHTML).
*
* @param {string} tagName The tag name to test against
* @param {Element} element The element to test with
* @returns boolean
*/
function matchesTag(tagName, element) {
return tagName.toLowerCase() === element.tagName.toLowerCase();
}
/**
* Check whether an element
* matches the root.
*
* @param {?String} selector In this case this is always passed through as null and not used
* @param {Element} element The element to test with
* @returns boolean
*/
function matchesRoot(selector, element) {
if (this.rootElement === window) {
return (
// Match the outer document (dispatched from document)
element === document ||
// The <html> element (dispatched from document.body or document.documentElement)
element === document.documentElement ||
// Or the window itself (dispatched from window)
element === window
);
}
return this.rootElement === element;
}
/**
* Check whether the ID of
* the element in 'this'
* matches the given ID.
*
* IDs are case-sensitive.
*
* @param {string} id The ID to test against
* @param {Element} element The element to test with
* @returns boolean
*/
function matchesId(id, element) {
return id === element.id;
}
/**
* Short hand for off()
* and root(), ie both
* with no parameters
*
* @return void
*/
Delegate.prototype.destroy = function () {
this.off();
this.root();
};
export default Delegate;