瀏覽代碼

back to childElementCount, add polyfill for IE

Hugo Di Francesco 4 年之前
父節點
當前提交
eab0e60e9b
共有 2 個文件被更改,包括 19 次插入1 次删除
  1. 18 0
      src/polyfills.js
  2. 1 1
      src/utils.js

+ 18 - 0
src/polyfills.js

@@ -9,3 +9,21 @@ import "events-polyfill/src/constructors/CustomEvent"
 import "events-polyfill/src/ListenerOptions"
 
 SVGElement.prototype.contains = SVGElement.prototype.contains || HTMLElement.prototype.contains
+
+// .childElementCount polyfill
+// from https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/childElementCount#Polyfill_for_IE8_IE9_Safari
+;(function(constructor) {
+    if (constructor &&
+        constructor.prototype &&
+        constructor.prototype.childElementCount == null) {
+        Object.defineProperty(constructor.prototype, 'childElementCount', {
+            get: function() {
+                var i = 0, count = 0, node, nodes = this.childNodes;
+                while (node = nodes[i++]) {
+                    if (node.nodeType === 1) count++;
+                }
+                return count;
+            }
+        });
+    }
+})(window.Node || window.Element);

+ 1 - 1
src/utils.js

@@ -23,7 +23,7 @@ export function isTesting() {
 export function warnIfMalformedTemplate(el, directive) {
     if (el.tagName.toLowerCase() !== 'template') {
         console.warn(`Alpine: [${directive}] directive should only be added to <template> tags. See https://github.com/alpinejs/alpine#${directive}`)
-    } else if (el.content.childNodes.length !== 1) {
+    } else if (el.content.childElementCount !== 1) {
         console.warn(`Alpine: <template> tag with [${directive}] encountered with multiple element roots. Make sure <template> only has a single child node.`)
     }
 }