A Pen by Daniel Hinds-Bond

Thumbnail
This awesome code was written by 007design, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright 007design ©
  • HTML
  • CSS
  • JavaScript
    <div>
  <button class="set-btn" data-set="test">Test</button>
  <div><span data-bind="test"></span></div>
  <button class="set-btn" data-set="test1">Test2</button>
  <div><span data-bind="test1"></span></div>
  <button class="set-btn" data-set="test2">Test3</button>
  <div><span data-bind="test2"></span></div>
  <button class="set-btn" data-set="test">Test4</button>
</div>

/*Downloaded from https://www.codeseek.co/007design/a-pen-by-daniel-hinds-bond-ZRpGRb */
    


/*Downloaded from https://www.codeseek.co/007design/a-pen-by-daniel-hinds-bond-ZRpGRb */
    (function() {
  const elements = document.querySelectorAll('[data-bind]'),
        scope = {};
  elements.forEach(function(element) {
    //execute scope setter
    var propToBind = element.getAttribute('data-bind');
    addScopeProp(propToBind);
    
    element.setValue = function(prop, value) {
      if (element.getAttribute('data-bind') === prop)
        scope[prop] = value;
    };

    //bind prop to elements
    function addScopeProp(prop){
      //add property if needed
      if(!scope.hasOwnProperty(prop)){
        //value to populate with newvalue
        var value;
        Object.defineProperty(scope, prop, {
          set: function (newValue) {
            value = newValue;
            elements.forEach(function(element){
              //change value to binded elements
              if(element.getAttribute('data-bind') === prop){
                element.innerHTML = newValue;
              }
            });
          },
          get: function(){
            return value;
          },
          enumerable: true
        });
      }
    }
  });
})();

(function() {
  const buttons = document.querySelectorAll('.set-btn');
  buttons.forEach(function(btn) {
    btn.addEventListener('click', function() {
      const button = this;
      document.querySelectorAll('[data-bind]').forEach(function(boundElem) {
        if (boundElem.setValue)
          boundElem.setValue(button.getAttribute('data-set'), button.innerHTML);
      })
    })
  })
})();

Comments