PluginProbe
Content Blocks Builder – Create blocks, repeater blocks with carousel, grid, popup layouts / trunk
Content Blocks Builder – Create blocks, repeater blocks with carousel, grid, popup layouts vtrunk
2.8.14 2.8.13 2.8.12 2.7.5 2.7.6 2.7.7 2.7.8 2.7.9 2.8.0 2.8.1 2.8.10 2.8.11 2.8.2 2.8.3 2.8.4 2.8.5 2.8.6 2.8.7 2.8.8 2.8.9 trunk 1.0.1 1.0.2 1.1.0 1.1.1 All 147 releases
content-blocks-builder / src / utils / dom / observer.js

observer.js in Content Blocks Builder – Create blocks, repeater blocks with carousel, grid, popup layouts trunk, at src/utils/dom/observer.js

69 lines 1.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 import { triggerEvent } from "./event";
2
3 class Observer {
4 constructor() {
5 this.observedContainers = new WeakMap();
6 this.pendingFrames = new WeakMap();
7 }
8
9 update(scope = document, args) {
10 triggerEvent(document, "cbb.observer.updated", { container: scope, args });
11 }
12
13 observe(container, args = {}) {
14 if (typeof container === "string") {
15 container = document.querySelector(container);
16 }
17
18 if (!(container instanceof HTMLElement)) {
19 return;
20 }
21
22 if (this.observedContainers.has(container)) {
23 return;
24 }
25
26 const observer = new MutationObserver((mutations) => {
27 /**
28 * Already scheduled
29 */
30 if (this.pendingFrames.has(container)) {
31 return;
32 }
33
34 const frame = requestAnimationFrame(() => {
35 this.pendingFrames.delete(container);
36
37 this.update(container, args);
38 });
39
40 this.pendingFrames.set(container, frame);
41 });
42
43 observer.observe(container, {
44 childList: true,
45 subtree: true,
46 });
47
48 this.observedContainers.set(container, observer);
49 }
50 }
51
52 const CBBObserver = new Observer();
53
54 /**
55 * Handle dynamic rendering
56 */
57 const observerUpdated = (fc) => {
58 document.addEventListener("cbb.observer.updated", (event) => {
59 const {
60 detail: { container, args },
61 } = event;
62 if (container) {
63 fc(container, args, event);
64 }
65 });
66 };
67
68 export { CBBObserver, observerUpdated };
69