-
Notifications
You must be signed in to change notification settings - Fork 7
/
arrive.js
461 lines (378 loc) · 14.4 KB
/
arrive.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
/*globals jQuery,Window,HTMLElement,HTMLDocument,HTMLCollection,NodeList,MutationObserver */
/*exported Arrive*/
/*jshint latedef:false */
/*
* arrive.js
* v2.4.1
* https://github.com/uzairfarooq/arrive
* MIT licensed
*
* Copyright (c) 2014-2017 Uzair Farooq
*/
var Arrive = (function(window, $, undefined) {
"use strict";
if(!window.MutationObserver || typeof HTMLElement === 'undefined'){
return; //for unsupported browsers
}
var arriveUniqueId = 0;
var utils = (function() {
var matches = HTMLElement.prototype.matches || HTMLElement.prototype.webkitMatchesSelector || HTMLElement.prototype.mozMatchesSelector
|| HTMLElement.prototype.msMatchesSelector;
return {
matchesSelector: function(elem, selector) {
return elem instanceof HTMLElement && matches.call(elem, selector);
},
// to enable function overloading - By John Resig (MIT Licensed)
addMethod: function (object, name, fn) {
var old = object[ name ];
object[ name ] = function(){
if ( fn.length == arguments.length ) {
return fn.apply( this, arguments );
}
else if ( typeof old == 'function' ) {
return old.apply( this, arguments );
}
};
},
callCallbacks: function(callbacksToBeCalled, registrationData) {
if (registrationData && registrationData.options.onceOnly && registrationData.firedElems.length == 1) {
// as onlyOnce param is true, make sure we fire the event for only one item
callbacksToBeCalled = [callbacksToBeCalled[0]];
}
for (var i = 0, cb; (cb = callbacksToBeCalled[i]); i++) {
if (cb && cb.callback) {
cb.callback.call(cb.elem, cb.elem);
}
}
if (registrationData && registrationData.options.onceOnly && registrationData.firedElems.length == 1) {
// unbind event after first callback as onceOnly is true.
registrationData.me.unbindEventWithSelectorAndCallback.call(
registrationData.target, registrationData.selector, registrationData.callback);
}
},
// traverse through all descendants of a node to check if event should be fired for any descendant
checkChildNodesRecursively: function(nodes, registrationData, matchFunc, callbacksToBeCalled) {
// check each new node if it matches the selector
for (var i=0, node; (node = nodes[i]); i++) {
if (matchFunc(node, registrationData, callbacksToBeCalled)) {
callbacksToBeCalled.push({ callback: registrationData.callback, elem: node });
}
if (node.childNodes.length > 0) {
utils.checkChildNodesRecursively(node.childNodes, registrationData, matchFunc, callbacksToBeCalled);
}
}
},
mergeArrays: function(firstArr, secondArr){
// Overwrites default options with user-defined options.
var options = {},
attrName;
for (attrName in firstArr) {
if (firstArr.hasOwnProperty(attrName)) {
options[attrName] = firstArr[attrName];
}
}
for (attrName in secondArr) {
if (secondArr.hasOwnProperty(attrName)) {
options[attrName] = secondArr[attrName];
}
}
return options;
},
toElementsArray: function (elements) {
// check if object is an array (or array like object)
// Note: window object has .length property but it's not array of elements so don't consider it an array
if (typeof elements !== "undefined" && (typeof elements.length !== "number" || elements === window)) {
elements = [elements];
}
return elements;
}
};
})();
// Class to maintain state of all registered events of a single type
var EventsBucket = (function() {
var EventsBucket = function() {
// holds all the events
this._eventsBucket = [];
// function to be called while adding an event, the function should do the event initialization/registration
this._beforeAdding = null;
// function to be called while removing an event, the function should do the event destruction
this._beforeRemoving = null;
};
EventsBucket.prototype.addEvent = function(target, selector, options, callback) {
var newEvent = {
target: target,
selector: selector,
options: options,
callback: callback,
firedElems: []
};
if (this._beforeAdding) {
this._beforeAdding(newEvent);
}
this._eventsBucket.push(newEvent);
return newEvent;
};
EventsBucket.prototype.removeEvent = function(compareFunction) {
for (var i=this._eventsBucket.length - 1, registeredEvent; (registeredEvent = this._eventsBucket[i]); i--) {
if (compareFunction(registeredEvent)) {
if (this._beforeRemoving) {
this._beforeRemoving(registeredEvent);
}
// mark callback as null so that even if an event mutation was already triggered it does not call callback
var removedEvents = this._eventsBucket.splice(i, 1);
if (removedEvents && removedEvents.length) {
removedEvents[0].callback = null;
}
}
}
};
EventsBucket.prototype.beforeAdding = function(beforeAdding) {
this._beforeAdding = beforeAdding;
};
EventsBucket.prototype.beforeRemoving = function(beforeRemoving) {
this._beforeRemoving = beforeRemoving;
};
return EventsBucket;
})();
/**
* @constructor
* General class for binding/unbinding arrive and leave events
*/
var MutationEvents = function(getObserverConfig, onMutation) {
var eventsBucket = new EventsBucket(),
me = this;
var defaultOptions = {
fireOnAttributesModification: false
};
// actual event registration before adding it to bucket
eventsBucket.beforeAdding(function(registrationData) {
var
target = registrationData.target,
observer;
// mutation observer does not work on window or document
if (target === window.document || target === window) {
target = document.getElementsByTagName("html")[0];
}
// Create an observer instance
observer = new MutationObserver(function(e) {
onMutation.call(this, e, registrationData);
});
var config = getObserverConfig(registrationData.options);
observer.observe(target, config);
registrationData.observer = observer;
registrationData.me = me;
});
// cleanup/unregister before removing an event
eventsBucket.beforeRemoving(function (eventData) {
eventData.observer.disconnect();
});
this.bindEvent = function(selector, options, callback) {
options = utils.mergeArrays(defaultOptions, options);
var elements = utils.toElementsArray(this);
for (var i = 0; i < elements.length; i++) {
eventsBucket.addEvent(elements[i], selector, options, callback);
}
};
this.unbindEvent = function() {
var elements = utils.toElementsArray(this);
eventsBucket.removeEvent(function(eventObj) {
for (var i = 0; i < elements.length; i++) {
if (this === undefined || eventObj.target === elements[i]) {
return true;
}
}
return false;
});
};
this.unbindEventWithSelectorOrCallback = function(selector) {
var elements = utils.toElementsArray(this),
callback = selector,
compareFunction;
if (typeof selector === "function") {
compareFunction = function(eventObj) {
for (var i = 0; i < elements.length; i++) {
if ((this === undefined || eventObj.target === elements[i]) && eventObj.callback === callback) {
return true;
}
}
return false;
};
}
else {
compareFunction = function(eventObj) {
for (var i = 0; i < elements.length; i++) {
if ((this === undefined || eventObj.target === elements[i]) && eventObj.selector === selector) {
return true;
}
}
return false;
};
}
eventsBucket.removeEvent(compareFunction);
};
this.unbindEventWithSelectorAndCallback = function(selector, callback) {
var elements = utils.toElementsArray(this);
eventsBucket.removeEvent(function(eventObj) {
for (var i = 0; i < elements.length; i++) {
if ((this === undefined || eventObj.target === elements[i]) && eventObj.selector === selector && eventObj.callback === callback) {
return true;
}
}
return false;
});
};
return this;
};
/**
* @constructor
* Processes 'arrive' events
*/
var ArriveEvents = function() {
// Default options for 'arrive' event
var arriveDefaultOptions = {
fireOnAttributesModification: false,
onceOnly: false,
existing: false
};
function getArriveObserverConfig(options) {
var config = {
attributes: false,
childList: true,
subtree: true
};
if (options.fireOnAttributesModification) {
config.attributes = true;
}
return config;
}
function onArriveMutation(mutations, registrationData) {
mutations.forEach(function( mutation ) {
var newNodes = mutation.addedNodes,
targetNode = mutation.target,
callbacksToBeCalled = [],
node;
// If new nodes are added
if( newNodes !== null && newNodes.length > 0 ) {
utils.checkChildNodesRecursively(newNodes, registrationData, nodeMatchFunc, callbacksToBeCalled);
}
else if (mutation.type === "attributes") {
if (nodeMatchFunc(targetNode, registrationData, callbacksToBeCalled)) {
callbacksToBeCalled.push({ callback: registrationData.callback, elem: targetNode });
}
}
utils.callCallbacks(callbacksToBeCalled, registrationData);
});
}
function nodeMatchFunc(node, registrationData, callbacksToBeCalled) {
// check a single node to see if it matches the selector
if (utils.matchesSelector(node, registrationData.selector)) {
if(node._id === undefined) {
node._id = arriveUniqueId++;
}
// make sure the arrive event is not already fired for the element
if (registrationData.firedElems.indexOf(node._id) == -1) {
registrationData.firedElems.push(node._id);
return true;
}
}
return false;
}
arriveEvents = new MutationEvents(getArriveObserverConfig, onArriveMutation);
var mutationBindEvent = arriveEvents.bindEvent;
// override bindEvent function
arriveEvents.bindEvent = function(selector, options, callback) {
if (typeof callback === "undefined") {
callback = options;
options = arriveDefaultOptions;
} else {
options = utils.mergeArrays(arriveDefaultOptions, options);
}
var elements = utils.toElementsArray(this);
if (options.existing) {
var existing = [];
for (var i = 0; i < elements.length; i++) {
var nodes = elements[i].querySelectorAll(selector);
for (var j = 0; j < nodes.length; j++) {
existing.push({ callback: callback, elem: nodes[j] });
}
}
// no need to bind event if the callback has to be fired only once and we have already found the element
if (options.onceOnly && existing.length) {
return callback.call(existing[0].elem, existing[0].elem);
}
setTimeout(utils.callCallbacks, 1, existing);
}
mutationBindEvent.call(this, selector, options, callback);
};
return arriveEvents;
};
/**
* @constructor
* Processes 'leave' events
*/
var LeaveEvents = function() {
// Default options for 'leave' event
var leaveDefaultOptions = {};
function getLeaveObserverConfig() {
var config = {
childList: true,
subtree: true
};
return config;
}
function onLeaveMutation(mutations, registrationData) {
mutations.forEach(function( mutation ) {
var removedNodes = mutation.removedNodes,
callbacksToBeCalled = [];
if( removedNodes !== null && removedNodes.length > 0 ) {
utils.checkChildNodesRecursively(removedNodes, registrationData, nodeMatchFunc, callbacksToBeCalled);
}
utils.callCallbacks(callbacksToBeCalled, registrationData);
});
}
function nodeMatchFunc(node, registrationData) {
return utils.matchesSelector(node, registrationData.selector);
}
leaveEvents = new MutationEvents(getLeaveObserverConfig, onLeaveMutation);
var mutationBindEvent = leaveEvents.bindEvent;
// override bindEvent function
leaveEvents.bindEvent = function(selector, options, callback) {
if (typeof callback === "undefined") {
callback = options;
options = leaveDefaultOptions;
} else {
options = utils.mergeArrays(leaveDefaultOptions, options);
}
mutationBindEvent.call(this, selector, options, callback);
};
return leaveEvents;
};
var arriveEvents = new ArriveEvents(),
leaveEvents = new LeaveEvents();
function exposeUnbindApi(eventObj, exposeTo, funcName) {
// expose unbind function with function overriding
utils.addMethod(exposeTo, funcName, eventObj.unbindEvent);
utils.addMethod(exposeTo, funcName, eventObj.unbindEventWithSelectorOrCallback);
utils.addMethod(exposeTo, funcName, eventObj.unbindEventWithSelectorAndCallback);
}
/*** expose APIs ***/
function exposeApi(exposeTo) {
exposeTo.arrive = arriveEvents.bindEvent;
exposeUnbindApi(arriveEvents, exposeTo, "unbindArrive");
exposeTo.leave = leaveEvents.bindEvent;
exposeUnbindApi(leaveEvents, exposeTo, "unbindLeave");
}
if ($) {
exposeApi($.fn);
}
exposeApi(HTMLElement.prototype);
exposeApi(NodeList.prototype);
exposeApi(HTMLCollection.prototype);
exposeApi(HTMLDocument.prototype);
exposeApi(Window.prototype);
var Arrive = {};
// expose functions to unbind all arrive/leave events
exposeUnbindApi(arriveEvents, Arrive, "unbindAllArrive");
exposeUnbindApi(leaveEvents, Arrive, "unbindAllLeave");
return Arrive;
})(window, typeof jQuery === 'undefined' ? null : jQuery, undefined);