JSFiddle - React, Tailwind, and code Playground

by koba04

HTML

<div><input type="text" class="hoge-bar"></input><span class="hoge-bar"></span></div>
<div><input type="text" class="hoge-baz"></input><span class="hoge-baz"></span></div>

JavaScript

var dataBinding = function(name, target) {
  
  Object.observe(target, function(changes) {
    console.log(changes);
    changes.forEach(function(change){
      list = document.querySelectorAll("span." + name + "-" + change.name);
      [].forEach.call(list, function(el) {
        var val = change.object[change.name];
        console.log(val);
        el.innerText = val;
      list2 = document.querySelectorAll("input." + name + "-" + change.name);
      [].forEach.call(list2, function(el) {
        el.value = val;
      });
      });
    });
  });
  for (key in target) {
    input = document.querySelectorAll("input." + name + "-" + key);
    [].forEach.call(input, function(el) {
      el.addEventListener('keyup', (function(key) {
        return function(e) {
          console.log(e.target.value);
          target[key] = e.target.value;
        };
      })(key));
    });

    target[key] = target[key] + " ";
  }
  return target;
};

obj = {
    bar: "bar",
    baz: "baz"
};
t = dataBinding('hoge', obj);

setTimeout(function() {
  t.bar = "yeah";
  t.baz = "yeahyeah";
}, 1000);