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>.
Example-
<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-
HTML
<div id="div_test">
<ul data-bind="foreach: products"><!--scope starts-->
<li><label data-bind="text: $index" ></label> <!--shows index count-->
<span data-bind="text: name"></span> <!--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>
</li>
<!--conditional binding template starts-->
</ul>
<!--scope ends-->
<button data-bind="click: onclick">Click</button><!--event binding-->
</div>
Javascript
Now, let have a bit more in to it. It will cover few real scenarios-
HTML
<div id="div_test">
<ul data-bind="foreach: products"><!--scope starts-->
<li><label data-bind="text: $index" ></label> <!--shows index count-->
<span data-bind="text: name"></span> <!--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>
</li>
<!--conditional binding template starts-->
</ul>
<!--scope ends-->
<button data-bind="click: onclick">Click</button><!--event binding-->
</div>
Javascript
function scope(){
var $scope=this;
//Json binding---->
$scope.products=[{name:"test",
address:"agarpara",
rate:22,
plot:{width:1110,height:800}
},
{name:"test2",
rate:18,
plot:{width:1500,height:600}}];
//Event binding------>
$scope.onclick=function(){
alert("Clicked");
};
}
ko.applyBindings(new scope(),document.getElementById("div_test"));//apply a scope by a dom id
Few more working examples are in here
No comments:
Post a Comment