GithubHelp home page GithubHelp logo

gjcarrow / 2-way-data-binding-in-plain-vanilla-javascript Goto Github PK

View Code? Open in Web Editor NEW

This project forked from namitamalik/2-way-data-binding-in-plain-vanilla-javascript

0.0 1.0 0.0 191 KB

This repository contains a demo explaining how to do 2 way data binding in plain vanilla JavaScript.

HTML 23.67% JavaScript 76.33%

2-way-data-binding-in-plain-vanilla-javascript's Introduction

2-way-data-binding-in-Plain-Vanilla-JavaScript

Whenever someone asks me about the advantages of AngularJS the first thing that simply comes into my mind is 2-way data binding.

For those who still aren't aware about it, 2-way data binding means when you change anything in your model, view gets updated and on changing anything in the view, model gets updated.

Everyone who knows Angular(having worked on it) or in fact has worked upon any other JavaScript framework(missed working on it) would actually know the beauty of this feature.

Well, now let's try to simply implement this feature in pur own plain vanilla JavaScript.

Let us take 4 text boxes to easily demonstrate 2-way data binding. Here is our small piece of HTML code:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>2 Way Data Binding</title>
</head>
<body>
Name: <input class="name" type="text">
<input class="name" type="text">
<hr />
Age: <input class="age" type="text">
<input class="age" type="text">
<script src="2WayDataBinding.js"></script>
</body>
</html>

Now, let's have a look at our magical JavaScript code which will do wonders for us:

var $scope = {};
(function () {
    var bindClasses = ["name", "age"];
    var attachEvent = function (classNames) {
        classNames.forEach(function (className) {
            var elements = document.getElementsByClassName(className);
            for (var index in elements) {
                elements[index].onkeyup = function () {
                    for (var index in elements) {
                        elements[index].value = this.value;
                    }
                }
            }
            Object.defineProperty($scope, className, {
                set: function (newValue) {
                    for (var index in elements) {
                        elements[index].value = newValue;
                    }
                }
            });
        });
    };
    attachEvent(bindClasses);
})();

Here is a detailed explanation of the above snippet:

  1. We have taken the classes of the elements on which we need to apply 2-way Data Binding in an array named bindClasses.

  2. Then we have an attachEvent which basically iterates through the classes passed in array bindClasses.

  3. We are extracting all the elements by using their class names document.getElementsByClassName(className).

  4. Once the elements are extracted we are binding onkeyup event on it. When this event is triggered it calls a function which stores the current value inside the element.

In this way we are successfully able to implement 2-way Data Binding on our HTML.

But how to update our model??

Here is the explanation of the rest of the part of the code which actually updates the value in our model:

  1. We have used object.defineProperty to define a property of an object. Here our object is $scope and property is className.

  2. Then we have a set function which serves as setter of the property.

  3. So, if you do something like - $scope.name="Hari", "Hari" would be passed as newValue, which would ultimately replace the value being displayed on the view through the following piece of code elements[index].value = newValue.

Hurray!! We have now implemented the 2-way Data Binding successfully.

| Please note that this is just a small piece of code demonstrating 2-way Data Binding using JavaScript this code can be improved a lot on the basis of element type.e We can also have a getter function for getting the value in $scope.name. But for the sake of simplicity I have deliberately avoided it.

You can checkout full working source code @ my github.

2-way-data-binding-in-plain-vanilla-javascript's People

Contributors

namitamalik avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.