ES6 spread syntax IE not supported

戏子无情 提交于 2019-11-29 08:38:15
T.J. Crowder

For all browsers, you can use Array.prototype.slice via call or apply (it works on any array-like object):

Array.prototype.slice.call(document.querySelectorAll('.row'))

About your updated question:

Im using this for 'click' event handling:

Array.prototype.slice.call(document.querySelectorAll('.row'))
    .forEach(function(header) {
      return header.addEventListener('click', function(e) {
        headerClick(e, header, header.querySelector('.exy'))
      });
    });

I wouldn't use querySelectorAll for this at all, I'd use event delegation. Presumably all of those .row elements are inside a common container (ultimately, of course, they're all in body, but hopefully there's a container "closer" to them than that). With event delegation, you do this:

  • Hook click just once, on the container

  • When a click occurs, check to see if it passed through one of your target elements en route to the container

For your quoted code, that looks something like this:

// A regex we'll reuse
var rexIsRow = /\brow\b/;
// Hook click on the container
document.querySelector("selector-for-the-container").addEventListener(
    "click",
    function(e) {
        // See if we find a .row element in the path from target to container
        var elm;
        for (elm = e.target; elm !== this; elm = elm.parentNode) {
            if (rexIsRow.test(elm.className)) {
                // Yes we did, call `headerClick`
                headerClick(e, elm, elm.querySelector('.exy'));
                // And stop looking
                break;
            }
        }
    },
    false
);

On more modern browsers, you could use elm.classList.contains("row") instead of the regular expression, but sadly not on IE9 or earlier.


That said, rather than maintaining a separate codebase, as gcampbell pointed out you could use ES6 (ES2015) features in your code and then transpile with a transpiler that converts them (well, the ones that can be converted, which is a lot of them) to ES5 syntax. Babel is one such transpiler.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!