Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 way data binding in JavaScript

Tags:

javascript

Two-way data binding refers to the ability to bind changes to an object’s properties to changes in the UI, and vice-versa.

Can we achieve 2-way data-binding with JavaScript?

Especially 2 Way Data Binding without Frameworks.

like image 740
Tony Avatar asked Aug 03 '17 16:08

Tony


People also ask

What are two-way data binding?

In a two-way binding, the data flow is bi-directional. This means that the flow of code is from ts file to Html file as well as from Html file to ts file. In order to achieve a two-way binding, we will use ngModel or banana in a box syntax.

What is data binding in JavaScript?

Data binding is the process that couples two data sources together and synchronizes them. With data binding, a change to an element in a data set automatically updates in the bound data set.

Why we use two-way data binding?

Two-way binding gives components in your application a way to share data. Use two-way binding to listen for events and update values simultaneously between parent and child components.

What is two-way data binding in AngularJS?

Two-way Binding Data binding in AngularJS is the synchronization between the model and the view. When data in the model changes, the view reflects the change, and when data in the view changes, the model is updated as well.


3 Answers

When an input is changed update the value, add a setter to the value which sets the inputs content. E.g 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 input will change. Changing the input changes person.age

like image 143
Jonas Wilms Avatar answered Oct 18 '22 04:10

Jonas Wilms


Yes, we can achieve the 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.

like image 32
Deepanshu Sharma Avatar answered Oct 18 '22 06:10

Deepanshu Sharma


Simple and working approach to two-way binding, only using vanilla JS.

<!-- index.html -->
<form action="#" onsubmit="vm.onSubmit(event, this)">
    <input onchange="vm.username=this.value" type="text" id="Username">
    <input type="submit" id="Submit">
</form>
<script src="vm.js"></script>

// vm.js - vanialla JS
let vm = {
    _username: "",
    get username() {
        return this._username;
    },
    set username(value) {
        this._username = value;
    },
    onSubmit: function (event, element) {
        console.log(this.username);
    }
}

JS Getters and Setters are quite nice for this - especially when you look at the browser support.

like image 21
Millard Avatar answered Oct 18 '22 04:10

Millard