Saturday, February 8, 2014

Knockout Js Quick Start

Knockout js is a Javascript library which follows MVVM. It interacts or binds model with dom(view) element using ViewModel.  Now through this we can bind text, events, conditions and iterators(loop). The syntax is- data-bind=”<kind of binding> :<scope param>.  

   <span data-bind="text: name"></span>

Another example-
   <div data-bind="if: address!=''"><span data-bind="text: address"></span></div>

Here, a conditional data binding is happening and under it, another text binding shown.

Now, let have a bit more in to it. It will cover few real scenarios-

   <div id="div_test">
    <ul data-bind="foreach: products"><!--scope starts-->
        <li><label data-bind="text: $index" ></label>&nbsp; <!--shows index count-->
            <span data-bind="text: name"></span>&nbsp;<!--conditional binding template starts-->
            <div data-bind="ifnot: rate > 20"><span data-bind="text: rate"></span></div>
            <div data-bind="with:plot">
                <span data-bind="text: width + '-' +height"></span></div> 
            <a data-bind="attr: {href:'#/'+name}" >click</a>          
            <div data-bind="if: address!=''"><span data-bind="text: address"></span></div>

<!--conditional binding template starts-->
<!--scope ends-->
     <button data-bind="click: onclick">Click</button><!--event binding-->


function scope(){
    var $scope=this;

//Json binding---->

//Event binding------>
ko.applyBindings(new scope(),document.getElementById("div_test"));//apply a scope by a dom id

Few more working examples are in here
Post a Comment