UNPKG

3.12 kBJavaScriptView Raw
1import canUseDOM from 'can-use-dom';
2
3import SimpleBar from './simplebar';
4import { getOptions } from './helpers';
5
6SimpleBar.initDOMLoadedElements = function() {
7 document.removeEventListener('DOMContentLoaded', this.initDOMLoadedElements);
8 window.removeEventListener('load', this.initDOMLoadedElements);
9
10 Array.prototype.forEach.call(
11 document.querySelectorAll('[data-simplebar]'),
12 el => {
13 if (
14 el.getAttribute('data-simplebar') !== 'init' &&
15 !SimpleBar.instances.has(el)
16 )
17 new SimpleBar(el, getOptions(el.attributes));
18 }
19 );
20};
21
22SimpleBar.removeObserver = function() {
23 this.globalObserver.disconnect();
24};
25
26SimpleBar.initHtmlApi = function() {
27 this.initDOMLoadedElements = this.initDOMLoadedElements.bind(this);
28
29 // MutationObserver is IE11+
30 if (typeof MutationObserver !== 'undefined') {
31 // Mutation observer to observe dynamically added elements
32 this.globalObserver = new MutationObserver(SimpleBar.handleMutations);
33
34 this.globalObserver.observe(document, { childList: true, subtree: true });
35 }
36
37 // Taken from jQuery `ready` function
38 // Instantiate elements already present on the page
39 if (
40 document.readyState === 'complete' ||
41 (document.readyState !== 'loading' && !document.documentElement.doScroll)
42 ) {
43 // Handle it asynchronously to allow scripts the opportunity to delay init
44 window.setTimeout(this.initDOMLoadedElements);
45 } else {
46 document.addEventListener('DOMContentLoaded', this.initDOMLoadedElements);
47 window.addEventListener('load', this.initDOMLoadedElements);
48 }
49};
50
51SimpleBar.handleMutations = mutations => {
52 mutations.forEach(mutation => {
53 Array.prototype.forEach.call(mutation.addedNodes, addedNode => {
54 if (addedNode.nodeType === 1) {
55 if (addedNode.hasAttribute('data-simplebar')) {
56 !SimpleBar.instances.has(addedNode) &&
57 new SimpleBar(addedNode, getOptions(addedNode.attributes));
58 } else {
59 Array.prototype.forEach.call(
60 addedNode.querySelectorAll('[data-simplebar]'),
61 function(el) {
62 if (
63 el.getAttribute('data-simplebar') !== 'init' &&
64 !SimpleBar.instances.has(el)
65 )
66 new SimpleBar(el, getOptions(el.attributes));
67 }
68 );
69 }
70 }
71 });
72
73 Array.prototype.forEach.call(mutation.removedNodes, removedNode => {
74 if (removedNode.nodeType === 1) {
75 if (removedNode.hasAttribute('[data-simplebar="init"]')) {
76 SimpleBar.instances.has(removedNode) &&
77 SimpleBar.instances.get(removedNode).unMount();
78 } else {
79 Array.prototype.forEach.call(
80 removedNode.querySelectorAll('[data-simplebar="init"]'),
81 el => {
82 SimpleBar.instances.has(el) &&
83 SimpleBar.instances.get(el).unMount();
84 }
85 );
86 }
87 }
88 });
89 });
90};
91
92SimpleBar.getOptions = getOptions;
93
94/**
95 * HTML API
96 * Called only in a browser env.
97 */
98if (canUseDOM) {
99 SimpleBar.initHtmlApi();
100}
101
102export default SimpleBar;