我正在考虑为BSN引入一个支持动态内容的新功能,所以我写了这样的东西:
示例代码
// some context
const initCallback = (parent: ParentNode) => {
// initialize all BSN components for the matched nodes in this parent
}
const removeDataAPI = (parent: ParentNode) => {
// remove all BSN components for the matched nodes in this parent
}
const addListener = (target: EventTarget, eventName: string, listener: EventListener) => {
return target.addEventListener(eventName, listener);
}
// overall callback
const loadCallback = (target?: ParentNode) => {
// Select the node that will be observed for mutations
const targetNode = target || document.body;
// Initialize first
initCallback(target);
// Options for the observer (which mutations to observe)
const config: MutationObserverInit = { childList: true, subtree: true };
// Callback function to execute when mutations are observed
const mutationCallback = (mutationList: MutationRecord[]) => {
const filteredList = mutationList.filter(({ addedNodes, removedNodes }) =>
[...addedNodes, ...removedNodes].every(
n => isHTMLElement(n) && !matches(n, '.popover,.tooltip,.offcanvas-backdrop,.modal-backdrop'),
),
);
for (const mutation of filteredList) {
if (mutation.type === 'childList') {
// console.log('A child node has been added or removed.', mutation);
[...mutation.addedNodes].forEach(n => initCallback(n as ParentNode));
[...mutation.removedNodes].forEach(n => removeDataAPI(n as ParentNode));
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(mutationCallback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
};
// Bulk initialize all components
if (document.body) loadCallback(document.body);
else {
addListener(document, 'DOMContentLoaded', () => loadCallback(), { once: true });
}
问题
loadCallback
有什么需要改进的地方吗?谢谢!