Knockout 1 Syntax and Basic usage

Basic operion using knockout js

by RajamohanShilpa A

HTML

<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"></script>
<div style='background-color:#f6f6f6;'>
    <p> <u><strong>Sample Application using Knockout - JS </strong></u>

        <p>Emp.Id : <strong data-bind='text: empId'></strong>

        </p>
        <p>Name : <strong data-bind='text: name'></strong>

        </p>
        <p>User Name :
            <input type='text' data-bind='value: userName' />
        </p>
        <p>Full Name : <strong data-bind='text: fname'></strong>

        </p>
        <p>
            <input type='button' data-bind='click: changeValue' value='Change' />
        </p>
    </p>
</div>

JavaScript

var ViewModel = function (Uname) {

    //ko.observable() --> Used to create the dynamic value         
    this.empId = ko.observable("024");
    this.name = Uname;
    this.userName = ko.observable(Uname);

    //ko.computed() --> used to combaine multiple observable value
    this.fname = ko.computed(function () {
        return this.userName() + this.empId();
    }, this);

    this.changeValue = function () {
        this.userName(this.userName().toUpperCase());
    };

};

//ko.applyBindings() --> trigger the knockout js functions
ko.applyBindings(new ViewModel("abcd"));