Blog

  • Implement two way binding in Vanilla Script.

    1) HTML Code

                   <div>Name: <input data-tw-bind="name" type="text"/><span data-tw-bind="name"></span></div>
             

    Here, create a custom attribute 'data-tw-bind', which will receive the name of the property to bind. It will allow us to select the element from DOM and to which property going to be binded.

    2) JS Code

                     
    
    (function() {
        var element = document.querySelectorAll('[data-tw-bind]'),
        scope = {};
        elements.forEach(function(element) {
            if(element.type === 'text'){
            var propToBind = element.getAttribute('data-tw-bind');
            element.onkeyup = function(){
                scope[propToBind] = element.value;
            }
        }
        });
    }();
    
        

    Here, what we are doing is get all the elements with our custom attribute. Iterate on those elements and get the property name and those of type ''text". "onkeyup" event, listener is going to set the value of the scope property to the element value. Now we need to update the value in DOM when the scope property changes. We add properties to the scope with a set and get function. Code for the same is below.

            function addScopeProp(property){
                if(!scope.hasOwnProperty(property)){
                    var value;
                    object.defineProperty(scope, property, {
                    set: function(newValue){
                        value = newValue;
                        elements.forEach(function(element){
                            if(element).getAttribute('data-tw-bind') === property){
                                if(element.type && element.type === 'text'){
                                    element.value = newValue;
                                } else If(!element.type){
                                    element.innerHTML = newValue;
                                }
                            }
                        }) ;    
                    },
                    get: function(){
                        return value;
                    },
                    enumerable: true
                    });
                }
            }          
        

    What does 'addScopeProp()' do: - Receive property name as a parameter. - Checks if the scope has already the property set. - Declares a variable "value" that is going to populate with the new value on set callback. - Calls the funcction "defineProperty" of object with the scope, the new property to add and the definition that is going to set. - Set callback have a functioon that receive the new value, populates the value variable and then it iterate through the elements. We need to call 'addScopeProp' function before onkeyup event.

Tags: javascript , AngularJS