├── README.md ├── app.js └── index.html /README.md: -------------------------------------------------------------------------------- 1 | # js-two-way-binding 2 | A simple two way binding implementation with plain javascript. 3 | 4 | For more information go to: 5 | 6 | [INFO](https://medium.com/frontend-fun/js-vanilla-two-way-binding-5a29bc86c787 "INFO") -------------------------------------------------------------------------------- /app.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | var elements = document.querySelectorAll('[data-tw-bind]'), 3 | scope = {}; 4 | elements.forEach(function(element) { 5 | //execute scope setter 6 | if(element.type === 'text'|| element.type === 'textarea'){ 7 | var propToBind = element.getAttribute('data-tw-bind'); 8 | addScopeProp(propToBind); 9 | element.onkeyup = function(){ 10 | scope[propToBind] = element.value; 11 | } 12 | }; 13 | 14 | //bind prop to elements 15 | function addScopeProp(prop){ 16 | //add property if needed 17 | if(!scope.hasOwnProperty(prop)){ 18 | //value to populate with newvalue 19 | var value; 20 | Object.defineProperty(scope, prop, { 21 | set: function (newValue) { 22 | value = newValue; 23 | elements.forEach(function(element){ 24 | //change value to binded elements 25 | if(element.getAttribute('data-tw-bind') === prop){ 26 | if(element.type && (element.type === 'text' || 27 | element.type === 'textarea')){ 28 | element.value = newValue; 29 | } 30 | else if(!element.type){ 31 | element.innerHTML = newValue; 32 | } 33 | } 34 | }); 35 | }, 36 | get: function(){ 37 | return value; 38 | }, 39 | enumerable: true 40 | }); 41 | } 42 | } 43 | }); 44 | 45 | log = function() { 46 | Object.keys(scope).forEach(function(key){ 47 | console.log(key + ': ' + scope[key]); 48 | }); 49 | } 50 | 51 | changeNameByCode = function() { 52 | scope.name = 'name Changed by Code'; 53 | } 54 | 55 | changeSurnameByCode = function() { 56 | scope.surname = 'surname Changed by Code'; 57 | } 58 | })(); 59 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Two Way Data Binding 6 | 7 | 8 | Name: 9 | 10 |
11 | Surname: 12 | 13 |
14 | 15 |
16 | 17 |
18 | 19 |
20 | 21 | 22 | 23 | --------------------------------------------------------------------------------