Two-way data binding in JavaScript

Two-way data binding refers to the ability to bind changes to object properties with changes in the user interface, and vice versa.

Is it possible to achieve two-way data binding with JavaScript?

Specifically, borderless two-way data binding.

+3


source to share


4 answers


When the input is changed, update the value, add an installer to the value that sets the contents of the inputs. For example, this element:

<input id="age">

      

And some js:

var person = (function(el){
 return {
   set age(v){
    el.value = v;
   },
   get age(){
     return el.value;
   }
 };
})(document.getElementById("age"));

      



So you can do:

 person.age = 15;

      

And the entrance will change. Changing the login changes person.age

+4


source


Yes, we can achieve two-way data binding using pure javascript.

twoWay=function(event) {
  var elem = document.getElementsByClassName(event.currentTarget.className);
  for(var key in elem){
    elem[key].value=event.currentTarget.value;
  }
}

      



You can check the jsfiddle .

+2


source


Yes, it is quite possible. It has been used by all major javascript frameworks (angularJS, angular ...).

You will find some examples here (this is a bit outdated but should give you some ideas) http://www.lucaongaro.eu/blog/2012/12/02/easy-two-way-data-binding-in-javascript/

+1


source


Yes indeed. There are frameworks like angular Js that provide full support for two way data binding. And if you want to achieve the same in vanilla js you can bind the value to the view

Eg. document.getElementById('test').value="This is a Test"

      

And to bind the value of the view to the controller, you can fire the onchange event in the html.

 <Input type="text" id="test" onchange="Func()">

      

+1


source







All Articles