做还是不做:使用MutationObserver进行组件初始化

问题描述 投票:0回答:0

我正在考虑为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 });
}

问题

  • 这种方法对于框架不可知论设计是否一致? (换句话说:这会以任何方式帮助 React/Solid/Vue 开发人员吗?)
  • 这在性能方面是否一致? (当用户超时或切换窗口并在用户返回页面时重新启动时,是否应该删除观察到的)
  • 这是否比原始的 Bootstrap jQuery 更好的方法,例如事件委托和单击时的组件初始化(BSN 仅将事件侦听器直接附加到目标)?
  • loadCallback 有什么需要改进的地方吗?

谢谢!

javascript reactjs vue.js initialization mutation-observers
© www.soinside.com 2019 - 2024. All rights reserved.