Loquicom 5 роки тому
батько
коміт
92a083e6b5
2 змінених файлів з 42 додано та 2 видалено
  1. 15 1
      src/index.html
  2. 27 1
      src/js/binder.js

+ 15 - 1
src/index.html

@@ -17,6 +17,10 @@
     <h3 data-bind="name"></h3>
     <h3 data-bind="test"></h3>
 
+    <div data-loop="aze">
+      <span data-val="a"></span>
+    </div>
+
     <input type="hidden" data-model="name" value="nom">
 
     <script type="text/javascript" src="../node_modules/jquery/dist/jquery.min.js"></script>
@@ -25,8 +29,18 @@
     <script type="text/javascript" src="js/binder.js"></script>
     <script type="text/javascript">
       var scope = binder({
-        test: 'aze'
+        test: 'aze',
+        aze: [
+          {
+            a: 'rty'
+          },
+          {
+            a: 'dfg'
+          }
+        ]
       });
+
+      looper(scope);
     </script>
   </body>
 </html>

+ 27 - 1
src/js/binder.js

@@ -2,6 +2,7 @@
 // Cache DOM elements
 const inputElements = document.querySelectorAll('[data-model]');
 const boundElements = document.querySelectorAll('[data-bind]');
+const loopElements = document.querySelectorAll('[data-loop]');
 
 /* --- Bind element --- */
 
@@ -70,4 +71,29 @@ function setBindValue(prop, newValue) {
   }
 }
 
-/* --- For each --- */
+/* --- For each --- */
+
+function looper(scope) {
+  for (let el of loopElements) {
+    let propName = el.getAttribute('data-loop');
+    let data = scope[propName];
+    let html = [];
+    // If data is an array (if not do nothing)
+    if (data && Array.isArray(data)) {
+      // Add info to replace value
+      for (let i = 0; i < data.length; i++) {
+        html.push(el.innerHTML.replace(/data-val="/g, 'data-index="' + i + '" data-val="'));
+      }
+      el.innerHTML = html.join("\n");
+
+      // Replace value for the current loop
+      let currentLoopElements = document.querySelectorAll('[data-loop=' + propName + ']');
+      currentLoopElements = currentLoopElements[0].childNodes;
+      for (const currentElement of currentLoopElements) {
+        if (currentElement.nodeName !== "#text" && currentElement.getAttribute('data-index')) {
+          currentElement.innerHTML = scope[propName][currentElement.getAttribute('data-index')][currentElement.getAttribute('data-val')];
+        }
+      }
+    }
+  }
+}