JavaScript

[JavaScript] IE에서 Event.path / Event.composed 사용을 위한 Polyfill

JayLee 2020. 4. 27. 17:21
반응형

Event.composedPath는 이벤트의 Path를 반환해줍니다. 그래서 이벤트가 어떤 흐름으로 도달했는지 알 수 있습니다.

 

caniuse.com에서 검색해보면 알 수 있지만, Event.composedPath() API는 IE에서 사용할 수 없습니다.

https://caniuse.com/#search=composedPath

 

Can I use... Support tables for HTML5, CSS3, etc

About "Can I use" provides up-to-date browser support tables for support of front-end web technologies on desktop and mobile web browsers. The site was built and is maintained by Alexis Deveria, with occasional updates provided by the web development commu

caniuse.com

그렇다면 어떻게할까요? 반드시 필요하다면 Polyfill을 구현하여 사용할 수 밖에 없습니다.

 

function eventPath(evt) {
  var path = (evt.composedPath && evt.composedPath()) || evt.path,
  target = evt.target;

  if (path != null) {
    // Safari doesn't include Window, and it should.
    path = (path.indexOf(window) < 0) ? path.concat([window]) : path;
    return path;
  }

  if (target === window) {
    return [window];
  }

  function getParents(node, memo) {
    memo = memo || [];
    var parentNode = node.parentNode;

    if (!parentNode) {
      return memo;
    } else {
      return getParents(parentNode, memo.concat([parentNode]));
    }
  }

  return [target]
    .concat(getParents(target))
    .concat([window]);
}

 

참고:

https://gist.github.com/leofavre/d029cdda0338d878889ba73c88319295

 

This function serves as a polyfill for Event.composedPath()

This function serves as a polyfill for Event.composedPath() - getEventPath.js

gist.github.com

 

반응형