-
Notifications
You must be signed in to change notification settings - Fork 0
/
formObserver.js
69 lines (60 loc) · 1.86 KB
/
formObserver.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
class FORMOBSERVER {
constructor(formObj) {
this.form = formObj;
this.formParents = [];
this.init();
}
init() {
this.addListener(this.form, this.formParents);
this.createObserver();
}
addListener(form, parentElement) {
Object.keys(form).forEach(function (formId) {
let FormEle = document.querySelector(formId);
if (FormEle !== null) {
parentElement.push(FormEle.parentElement);
FormEle.addEventListener("formSub", (e) => {
if (e.detail.success == true) {
Forms[formId]();
}
});
}
})
}
createObserver() {
const callback = function (mutationsList, observer) {
for (const mutation of mutationsList) {
if (
mutation.type === "attributes" &&
mutation.target.classList.contains("w-form-done")
) {
const formSubEvt = new CustomEvent("formSub", { detail: { success: true } });
const $form = mutation.target.parentElement.querySelector("form");
const formData = new FormData($form);
formSubEvt.formData = formData;
$form.dispatchEvent(formSubEvt);
}
}
};
// Create an observer instance linked to the callback function
this.observer = new MutationObserver(callback);
this.callObserver(this.formParents, this.observer);
}
callObserver(formParents, observer) {
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };
// Start observing the target node for configured mutations
formParents.forEach(function (form) {
observer.observe(form, config);
});
}
}
function observeBehaviour() {
console.log("working")
}
const Forms = {
".from-block": observeBehaviour,
"[data='form-two']": observeBehaviour,
"#form-3": observeBehaviour,
}
new FORMOBSERVER(Forms);