vue defined instructions from memory leaks caused solve

  vue custom instruction is relatively easy to cause a memory leak place, the reason is that the instruction is usually given element binding event, but if you forget to understand the tie, it will have a memory leak problem.

  Look at the code below:

    directives: { 
      Scroll: { 
        inserted The (EL, CB) { 
          // not an element node is not provided callback || 
          IF (! == el.nodeType . 1 ! || CB) return 
          the let Direct = ' Down ' 
          the let rollHeight = 0 

          the let getScrollEventTarget = (target) => {
             the while (target.nodeType === . 1 && target.tagName! == ' the BODY ' && el.tagName! == ' the HTML ' ) {
               var overflowY = getComputedStyle(target).overflowY
              if (overflowY === 'scroll' || overflowY === 'auto') {
                return target
              }
              target = target.parentNode
            }
            return window
          }

          let targetNode = getScrollEventTarget(el)

          let scrollListener = () => {
            if (targetNode.scrollTop > rollHeight) {
              direct = 'down'
            } else {
              direct = 'up'
            }
            rollHeight = targetNode.scrollTop
            cb.value(rollHeight, direct)
          }

          el.unbindEventListener = () => {
            targetNode.removeEventListener('scroll', scrollListener)
          }
          targetNode.addEventListener('scroll', scrollListener)
        },
         // unbind (el) {
         //  if (el.unbindEventListener) {
         //    el.unbindEventListener()
         //  }
        // }
      }
    }

  At first, I forgot some comments unbind method, resulting in a memory leak, scroll to the element method binding, will always exist memory. Lead to a situation, that is, for example, I entered the page scroll to page 3, go out, and then point to a page, if you scroll to page 4, it will request twice, once on page 4 of the last page, and once the page page 4, when you quit, and then into a page, if you scroll down page 5, will request three times (on the page, the page and this page), this is a typical event unsolved tie lead to memory leaks.

  So it is necessary to unbundle the elements, fortunately vue instructions provide unbind hook function, but there are still technical point is clever:

  1, we scroll element may be bound to the parent element and so on, we need to look up layer by layer

  2, unbundling is the time we need to find the parent element, and so on, and then also need a corresponding method remove, then it certainly can not write at once unbind years, so we can insert hook function, give el binding a unbundling event el.unbindEventListener, you can directly call the hook function in the unbind.

Guess you like

Origin www.cnblogs.com/goloving/p/11266974.html