-
Notifications
You must be signed in to change notification settings - Fork 0
/
bindly.js
738 lines (613 loc) · 29.8 KB
/
bindly.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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
/*
Version: v1.2.5 ( updates @ github.com/jridyard/bindly )
Creator: Joe Ridyard ( github.com/jridyard )
*/
class Bind {
constructor(params) {
if (!params) return;
function keyNotListed(key) { return !Object.keys(params).includes(key) }
// if the user did not pass a target, we cant do anything and need to warn them.
if (keyNotListed('target')) {
console.error('Bindly: You must pass a target element selector. Example: Bindly({target: ".my-element"})');
this.dontInitialize = true;
}
if (params.target?.length == 0) {
console.error('Bindly: You must pass a target element selector. Example: Bindly({target: ".my-element"})');
this.dontInitialize = true;
}
// Set defaults for params that may not be passed and need to be set to TRUE.
// // if (keyNotListed('duplicate')) params['duplicate'] = false
if (keyNotListed('bindAll')) params['bindAll'] = true
if (keyNotListed('rebind')) params['rebind'] = true
if (keyNotListed('hard-rebind')) params['hard-rebind'] = true
if (keyNotListed('logs')) params['logs'] = true
if (keyNotListed('delay')) params['delay'] = 1
if (keyNotListed('groupId')) params['groupId'] = this.guidGenerator()
this.bindlyStyleDetails = {
'original': {},
'duplicate': {}
}
this.removalObservers = {
'original': {},
'duplicate': {}
}
this.attributeObservers = {
'original': {},
'duplicate': {}
}
this.duplicateElms = {} // contains ID's of elements that have been injected by bindly and a link to the element
this.originalElms = {} // tracks ID's of the original elements we injected
this.params = params
}
guidGenerator() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+"-"+S4()+"-"+S4());
}
awaitDOM() {
if (document.readyState === 'loading') {
window.addEventListener('DOMContentLoaded', async (e) => {
this.awaitReadyStateComplete()
})
}
else if (document.readyState === 'interactive') {
this.awaitReadyStateComplete()
}
else {
this.waitForElm()
}
}
awaitReadyStateComplete() {
if (document.readyState === 'complete' || !this.params.awaitDOM) {
return this.waitForElm()
}
this.pageStateObserver = new MutationObserver(mutations => {
if (document.readyState === 'complete') {
this.pageStateObserver.disconnect()
this.waitForElm()
}
});
this.pageStateObserver.observe(document.body, {
childList: true,
subtree: true
})
}
waitForElm() {
// no need to ever have waitForElm running more than once at a time.
if (this.awaitingElm) return
this.awaitingElm = true
if (this.awaitPresenceObserver) this.awaitPresenceObserver.disconnect() // if we are on bindall then we are already listening for new elements to be created, this would cause a recursive loop if don't disconnect here first in that.
new Promise(resolve => {
// --- JQUERY MODE --- \\
if (this.params.jquery == true) {
const element_list = $(`${this.params.target}:not([bindly="bound"])`)
if (element_list.length >= 1) {
const element = element_list[0]
const correctElement = this.checkRules(element)
if (correctElement) return resolve(element)
}
this.awaitPresenceObserver = new MutationObserver(mutations => {
const element_list = $(`${this.params.target}:not([bindly="bound"])`)
if (element_list.length >= 1) {
const element = element_list[0]
const correctElement = this.checkRules(element)
if (correctElement) {
resolve(element)
this.awaitPresenceObserver.disconnect();
}
}
});
this.initializePresenceObserver()
}
// --- REGULAR MODE --- \\
else {
const element = document.querySelector(`${this.params.target}:not([bindly="bound"])`)
if (element) {
const correctElement = this.checkRules(element)
if (correctElement) return resolve(element)
}
this.awaitPresenceObserver = new MutationObserver(mutations => {
const element = document.querySelector(`${this.params.target}:not([bindly="bound"])`)
if (element) {
const correctElement = this.checkRules(element)
if (correctElement) {
resolve(element)
this.awaitPresenceObserver.disconnect();
}
}
});
this.initializePresenceObserver()
}
}).then((originalElement) => {
// waitForElm has no completed a cycle, next time we call WFE, we need to make sure it runs.
this.awaitingElm = false
this.bindElement(originalElement)
})
}
initializePresenceObserver() {
try {
this.awaitPresenceObserver.observe(document.body, {
childList: true,
subtree: true
});
} catch (err) {
if (err.toString().includes('TypeError: Failed to execute \'observe\' on \'MutationObserver\': parameter 1 is not of type \'Node\'.')) {
if (!this.params.awaitDOM) console.error("Bindly: Body element not found. This is most likely an issue with how the page renders elements and bindly being instantied too quickly. To fix this, try setting the paramater 'awaitDOM' to true or adjust bindly's initialization delay by setting the 'delay' parameter, which takes an int in milliseconds.")
if (this.params.awaitDOM) console.error("Bindly: Body element not found in document. Please report this error to the developer.")
}
console.error(err)
}
}
checkRules(element) {
if (!this.params.rules) return true
const passed = this.params.rules(element)
if (passed) return true
if (!passed) {
// we dont want to create a recursive loop of re-checking if it failed to pass the rules.
// set the attr to avoid double check and simply dont resolve afterwards.
element.setAttribute('bindly', 'bound')
element.setAttribute('bindly-rules', 'failed')
return false
}
}
bindElement(originalElement) {
const bindly_id = this.guidGenerator()
originalElement.setAttribute('bindly-id', bindly_id)
originalElement.setAttribute('bindly-type', 'original')
originalElement.setAttribute('bindly', 'bound')
originalElement.setAttribute('bindly-group-id', this.params.groupId)
const originalElm = originalElement
this.originalElms[bindly_id] = originalElm
if (!this.params.duplicate) {
// element is created, run OnCreated callback if user passed one
if (this.params.onCreated) {
const createdInfo = {
'originalElement': originalElm,
'duplicateElement': null,
}
this.onCreated(createdInfo)
}
}
this.trackElmDeletion(originalElement, {
"bindly_element_id": bindly_id,
"bindly-type": 'original'
})
if (this.params.duplicate) {
const targetToClone = originalElement
this.initializeDuplicateElm(targetToClone)
}
const manipulationParams = this.params.originalElement // .adjustments?
if (manipulationParams) this.manipulateElm(originalElm, manipulationParams)
if (this.params.onMutation) {
this.bindlyStyleDetails['original'][bindly_id] = this.getCurrentStyles(originalElm)
this.onMutation(originalElm, 'original', bindly_id)
}
if (this.params.bindAll) this.waitForElm()
}
pairElements(newElement, originalElement) {
const originalElm_id = originalElement.getAttribute('bindly-id')
if (!originalElm_id) {
return console.error("Bindly: Cannot pair to a non bindly element. The original element you passed has no bindly-id attribute.")
}
const bindly_id = this.guidGenerator()
newElement.setAttribute('bindly', 'bound')
newElement.setAttribute('bindly-type', 'duplicate')
newElement.setAttribute('bindly-group-id', this.params.groupId)
newElement.setAttribute('bindly-id', bindly_id)
newElement.setAttribute('bindly-pair-id', originalElm_id)
this.trackElmDeletion(newElement)
if (this.params.onMutation) {
this.bindlyStyleDetails['duplicate'][bindly_id] = this.getCurrentStyles(newElement)
this.onMutation(newElement, 'duplicate', bindly_id)
}
}
rebind(e) {
// rebind is useful when a duplicate element is removed DIRECTLY.
// Sometimes, certain sites will randomly jettison our duplicate element.
// this method allows us to rebind the original element and maintain a seamless look through the tumultous element rendering process.
const originalElement = document.querySelector(`[bindly-id="${e.target.getAttribute('bindly-pair-id')}"]`);
if (originalElement) {
if (this.params.logs) console.warn('Bindly: Duplicate element removed directly. The original element was still present. Bindly has re-injected the duplicate element. Turn this feature off by setting the paramater "rebind" to false.')
this.bindElement(originalElement)
}
else {
if (this.params.logs) console.warn('Bindly: Duplicate element removed directly. The original element was NOT still present. Bindly has run some fairly sketchy code to try to solve the problem. If you are having issues, turn this feature off by setting the paramater "hard-rebind" to false.')
if (this.params['hard-rebind']) {
// this is straight up sketchy code.
// there is an extremely rare issue when loading a single page app that causes a misfire and rebind fails, but the elements inexpciably retain bindly properties???
// the specific issue was found on zillow.com when loading in the home details modal for the home fact bullets. ( selector = ".ds-data-view-list .dpf__sc-2arhs5-0.ecJCxh" )
// the following solution fixed the problem, but I fear it could cause problems for otherwise functional bindly instances in the future.
document.querySelectorAll(`[bindly-group-id="${this.params.groupId}"]`).forEach(elm => {
elm.removeAttribute('bindly')
});
}
}
}
trackElmDeletion(target, attributes=null) {
var element_type;
var bindly_element_id;
if (attributes) {
element_type = attributes['bindly-type']
bindly_element_id = attributes['bindly_element_id']
} else {
element_type = target.getAttribute('bindly-type')
bindly_element_id = target.getAttribute('bindly-id')
}
new Promise(resolve => {
let observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var nodes = Array.from(mutation.removedNodes)
var directMatch = nodes.indexOf(target) > -1
var parentMatch = nodes.some(parent => parent.contains(target))
if (directMatch || parentMatch) {
observer.disconnect()
resolve({
'elementType': element_type,
'target': target,
'mutation': mutation,
'destructionMethod': directMatch ? "direct-match" : parentMatch ? "parent-match" : "unknown",
})
}
})
})
var config = {
subtree: true,
childList: true
}
observer.observe(document.body, config)
// if (this.removalObservers?.element_type?.bindly_element_id) this.removalObservers.element_type.bindly_element_id = observer
this.removalObservers[element_type][bindly_element_id] = observer
}).then((removalEventDetails) => {
this.onDestroyed(removalEventDetails)
this.waitForElm()
})
}
onMutation(target_element, bindly_element_type, bindly_element_id) {
// collect information on attribute changes
var changeInfo = {}
target_element.setAttribute = (...args) => {
changeInfo = {
'attribute': args[0],
'old_value': target_element.getAttribute(args[0]),
'new_value': args[1],
}
return HTMLElement.prototype.setAttribute.apply(target_element, args);
};
target_element.removeAttribute = (...args) => {
changeInfo = {
'attribute': args[0],
'old_value': target_element.getAttribute(args[0]),
'new_value': null,
}
return HTMLElement.prototype.removeAttribute.apply(target_element, args);
};
new Promise(resolve => {
let observer = new MutationObserver(function (records) {
records.forEach(function (record) {
try {
observer.disconnect()
resolve(record)
} catch (err) { /* supress err */ }
});
});
observer.observe(target_element, {
characterData: true,
childList: true,
subtree: true,
attributes: true,
characterDataOldValue: true
});
this.attributeObservers[bindly_element_type][bindly_element_id] = observer
}).then((record) => {
var TARGET = target_element
const bindly_id = TARGET.getAttribute('bindly-id') ? TARGET.getAttribute('bindly-id') : this.guidGenerator()
// we use .then() to access our class information without being limited by the mutation observers class.
// re-instantiate observer right away since we don't actually want it to be off
if (bindly_element_type == 'original') this.onMutation(TARGET, 'original', bindly_id)
if (bindly_element_type == 'duplicate') this.onMutation(TARGET, 'duplicate', bindly_id)
// the below inline if statement is irrelevant with the current version of bindly. We will ALWAYS have it present. More so just a backup in the unlikely case something goes wrong.
// TODO: Get the guts up to remove the crutch if statement below...
const previousStyleDetails = this.bindlyStyleDetails[bindly_element_type][bindly_id] ? this.bindlyStyleDetails[bindly_element_type][bindly_id] : {}
this.bindlyStyleDetails[bindly_element_type][bindly_id] = this.getCurrentStyles(target_element)
var styleChangeLog = {};
const newStyleDetails = this.bindlyStyleDetails[bindly_element_type][bindly_id]
const newStyleDetailsKeys = Object.keys(newStyleDetails)
for (var i=0; i < newStyleDetailsKeys.length; i++) {
var newStlyeKey = newStyleDetailsKeys[i]
if (previousStyleDetails[newStlyeKey] != newStyleDetails[newStlyeKey]) {
styleChangeLog[newStlyeKey] = {
'old_value': previousStyleDetails[newStlyeKey],
'new_value': newStyleDetails[newStlyeKey],
}
}
}
const attribute_change_record = {
'attributeTrigger': record.attributeName,
'elementType': bindly_element_type,
'target': target_element,
'mutation': record,
'styleChanges': styleChangeLog,
'attributeChanges': changeInfo
}
changeInfo = {} // reset changeInfo
this.params.onMutation(attribute_change_record)
})
}
getCurrentStyles(elm) {
const computedStyles = window.getComputedStyle(elm)
const computedStyleKeys = Object.keys(computedStyles)
var allStyles = {}
for (var i=0; i < computedStyleKeys.length; i++) {
var styleKey = computedStyleKeys[i];
if (isNaN(styleKey)) allStyles[styleKey] = computedStyles[styleKey]
}
return allStyles
}
initializeDuplicateElm(targetToClone) {
// targetToClone == originalElm
const duplicateElm = this.dupliacteElm(targetToClone)
const bindly_id = this.guidGenerator()
duplicateElm.setAttribute('bindly-id', bindly_id)
duplicateElm.setAttribute('bindly-type', 'duplicate')
this.duplicateElms[bindly_id] = duplicateElm
duplicateElm.setAttribute('bindly-group-id', this.params.groupId)
// track removal of the bound element
this.trackElmDeletion( duplicateElm )
const manipulationParams = this.params.duplicateElement // .adjustments?
if (manipulationParams) this.manipulateElm(duplicateElm, manipulationParams)
// 'insert' is not a manipulation parameter, it is a global param. That way, you can place it directly after 'duplicate' = true so you know how it will be injected at an easy glance.
typeof this.params.insert === 'string' ? this.params.insert.toLowerCase() == 'before' ? this.insertBefore(targetToClone, duplicateElm) : this.insertAfter(targetToClone, duplicateElm) : this.insertAfter(targetToClone, duplicateElm)
// set Elements that are bound to each other
const duplicateElmId = duplicateElm.getAttribute('bindly-id')
const originalElmId = targetToClone.getAttribute('bindly-id')
targetToClone.setAttribute('bindly-pair-id', duplicateElmId)
duplicateElm.setAttribute('bindly-pair-id', originalElmId)
// onMutation =>
if (this.params.onMutation) {
this.bindlyStyleDetails['duplicate'][bindly_id] = this.getCurrentStyles(duplicateElm)
this.onMutation(duplicateElm, 'duplicate', bindly_id)
}
// onCreated =>
if (this.params.onCreated) {
const createdInfo = {
'originalElement': targetToClone,
'duplicateElement': duplicateElm,
}
this.onCreated(createdInfo)
}
}
manipulateElm(element, manipulationParams) {
if (manipulationParams.id) this.setId(element, manipulationParams.id)
if (manipulationParams.className) this.setClass(element, manipulationParams.className)
if (manipulationParams.addClasses) this.addClasses(element, manipulationParams.addClasses)
if (manipulationParams.setAttributes) (() => {
for (let i=0; i < Object.keys(manipulationParams.setAttributes).length; i++) {
var attrKey = Object.keys(manipulationParams.setAttributes)[i]
var attrVal = Object.values(manipulationParams.setAttributes)[i]
this.addAttribute(element, attrKey, attrVal)
}
})()
if (manipulationParams.addEventListeners) (() => {
for (let i=0; i < Object.keys(manipulationParams.addEventListeners).length; i++) {
var listenerKey = Object.keys(manipulationParams.addEventListeners)[i]
var listenerVal = Object.values(manipulationParams.addEventListeners)[i]
this.addListener(element, listenerKey, listenerVal)
}
})()
if (manipulationParams.innerHTML) this.setInnerHTML(element, manipulationParams.innerHTML)
this.setDisplay(element, manipulationParams.display)
}
dupliacteElm(targetToClone) {
const duplicateElm = targetToClone.cloneNode(true)
return duplicateElm
}
setId(element, id) {
element.id = id
}
setClass(element, className) {
element.className = className
}
addClasses(element, classes) {
element.classList.add(...classes)
}
addAttribute(element, attrName, attrValue) {
element.setAttribute(attrName, attrValue)
}
addListener(element, listenFor, callback) {
element.addEventListener(listenFor, callback)
}
setInnerHTML(element, innerHTML) {
element.innerHTML = innerHTML
}
setDisplay(element, display) {
if (display === false || display === 'none') element.style.display = 'none'
}
insertAfter(targetToClone, duplicateElm) {
targetToClone.parentNode.insertBefore(duplicateElm, targetToClone.nextSibling)
}
insertBefore(targetToClone, duplicateElm) {
targetToClone.parentNode.insertBefore(duplicateElm, targetToClone)
}
onCreated(createdInfo) {
this.params.onCreated(createdInfo)
}
onDestroyed(removalEventDetails) {
const target_removed = removalEventDetails.target
target_removed.removeAttribute('bindly')
const uuid_removed = target_removed.getAttribute('bindly-id')
delete this.duplicateElms[uuid_removed]
delete this.originalElms[uuid_removed]
if (removalEventDetails.elementType == 'duplicate' && removalEventDetails.destructionMethod == 'direct-match') {
if (this.params.rebind) this.rebind(removalEventDetails)
}
if (this.params.onDestroyed) this.params.onDestroyed(removalEventDetails)
}
validateElements() {
// There are super rare cases where elements will be removed, but reinjected by the page.
// This causes our onDestroy method to remove them from our global object, but they are still in the DOM.
// When you run .unbind(), these rare edge case elements will not be removed from the DOM.
// If the user passed a groupId, we can do a manual check for elements missing from our global object to make sure we cover this edge case.
const groupId = this.params.groupId
const originalElements = document.querySelectorAll(`[bindly-group-id="${ groupId }"][bindly-type="original"]`)
for (var i=0; i < originalElements.length; i++) {
var originalElement = originalElements[i]
var originalElmId = originalElement.getAttribute('bindly-id')
if (!Object.keys(this.originalElms).includes(originalElmId)) {
this.originalElms[originalElmId] = originalElement
}
}
const duplicateElements = document.querySelectorAll(`[bindly-group-id="${ groupId }"][bindly-type="duplicate"]`)
for (var i=0; i < duplicateElements.length; i++) {
var duplicateElement = duplicateElements[i]
var duplicateElmId = duplicateElement.getAttribute('bindly-id')
if (!Object.keys(this.duplicateElms).includes(duplicateElmId)) {
this.duplicateElms[duplicateElmId] = duplicateElement
}
}
}
getElements() {
const groupId = this.params.groupId
var elements = {
'originalElements': [],
'duplicateElements': []
}
const originalElements = document.querySelectorAll(`[bindly-group-id="${ groupId }"][bindly-type="original"]`)
for (var i=0; i < originalElements.length; i++) {
var originalElement = originalElements[i]
elements['originalElements'].push(originalElement)
}
const duplicateElements = document.querySelectorAll(`[bindly-group-id="${ groupId }"][bindly-type="duplicate"]`)
for (var i=0; i < duplicateElements.length; i++) {
var duplicateElement = duplicateElements[i]
elements['duplicateElements'].push(duplicateElement)
}
return elements
}
displayOriginalElms(originalDisplay = 'block') {
const targets = Object.values(this.originalElms)
for (var i=0; i < targets.length; i++) {
var target = targets[i]
target.style.display = originalDisplay
}
}
unbind(onDestroyCallback) {
if (this.enabled) {
this.validateElements()
// this callback allows the user to modify the originalElm back to its initial state and collect metadata or w/e they want from the duplicated elm.
const duplicateElements = Object.assign({}, this.duplicateElms)
const originalElements = Object.assign({}, this.originalElms)
if (onDestroyCallback) onDestroyCallback({'originalElements': Object.values(originalElements), 'duplicateElements': Object.values(duplicateElements) })
if (this.awaitPresenceObserver) this.awaitPresenceObserver.disconnect() // it's possible for the element to already be present and bindAll be set to false. This would cause the awaitPresenceObserver never to have been created.
this.disconnectObservers(this.removalObservers, 'original')
this.disconnectObservers(this.attributeObservers, 'original')
this.removalObservers['original'] = {}
this.attributeObservers['original'] = {}
if (this.params.duplicate) {
this.disconnectObservers(this.removalObservers, 'duplicate')
this.disconnectObservers(this.attributeObservers, 'duplicate')
this.removalObservers['duplicate'] = {}
this.attributeObservers['duplicate'] = {}
}
const elementsToRemove = {
'originalElms': this.originalElms,
'duplicateElms': this.duplicateElms
}
this.destroyElements(elementsToRemove)
this.awaitingElm = false
this.enabled = false
}
}
destroyElements(elements) {
const originalElmsIds = Object.keys(elements.originalElms)
for (var i=0; i < originalElmsIds.length; i++) {
const originalElmBoundId = originalElmsIds[i]
const originalElement = elements.originalElms[originalElmBoundId]
if (originalElement) {
originalElement.removeAttribute('bindly')
originalElement.removeAttribute('bindly-type')
originalElement.removeAttribute('bindly-id')
originalElement.removeAttribute('bindly-pair-id')
originalElement.removeAttribute('bindly-group-id')
}
delete elements.originalElms[originalElmBoundId]
}
const injectedElmIds = Object.keys(elements.duplicateElms)
for (var i=0; i < injectedElmIds.length; i++) {
const injectedElmId = injectedElmIds[i]
const elementInjected = elements.duplicateElms[injectedElmId]
if (elementInjected) {
elementInjected.remove()
}
delete elements.duplicateElms[injectedElmId]
}
}
bind() {
if (this.dontInitialize) return
if (!this.enabled) {
if (this.params.awaitDOM) {
this.enabled = true
this.awaitDOM() // only awaits dom if not already fully loaded, otherwise runs right away.
return
}
// if never intialized...
if (!this.initialized) {
// If we have yet to initialize, we need to wait a single millisecond for the body to load in case the user is running bindly at the same time the body is being loaded.
// The body ALWAYS loads in the first millisecond.
return setTimeout(() => {
this.enabled = true
this.initialized = true
this.waitForElm()
}, this.params.delay);
}
// else if already initialized...
this.enabled = true
this.waitForElm()
}
}
disconnectObservers(observersType, elementType) {
const observersToDisconnect = Object.keys(observersType[elementType])
for (var i=0; i < observersToDisconnect.length; i++) {
const observerKey = observersToDisconnect[i]
const observer = observersType[elementType][observerKey]
observer.disconnect()
}
}
static async waitFor(selector, jquery = false) {
// DEFAULT
if (jquery == false) return new Promise(resolve => {
const target = document.querySelector(selector)
if (target) return resolve(target)
let observer = new MutationObserver(mutations => {
const target = document.querySelector(selector)
if (target) {
resolve(target);
observer.disconnect();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
})
})
// JQUERY MODE:
return new Promise(resolve => {
const target = $(selector)[0]
if (target) return resolve(target)
let observer = new MutationObserver(mutations => {
const target = $(selector)[0]
if (target) {
resolve(target);
observer.disconnect();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
});
}
}
function Bindly(params) {
return new Bind(params)
}