KnockoutJS is based on Model-View-ViewModel (MVVM) pattern.Below is the simple example of KnockoutJS.The application accept first name and last name and return the full name.Here we will study the different part of Model-View-ViewModel pattern.
Example
Example
<!DOCTYPE
html>
<body>
<script
src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
<table>
<tr>
<td>First
Name :
</td>
<td><input
data-bind="value:
firstName"
/>
</td>
</tr>
<tr>
<td>Second
Name :
</td>
<td><input
data-bind="value:
SecondName"
/>
</td>
</tr>
<tr>
<td>Your
Full Name :
</td>
<td><strong
data-bind
=
"text:
fullname"></strong>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
</tr>
</table>
<script>
<!--"viewmodel"--
>
function
AppViewModel() {
this.firstName
= ko.observable("");
this.SecondName
= ko.observable("");
this.fullname
= ko.computed(function
()
{
{
return
this.firstName()
+ "
"
+ this.SecondName();
},
this);
}
//
Activattion code
ko.applyBindings(new
AppViewModel());
</script>
</body>
Output
The full application has several part
1.We have added KnockoutJS CDN url ,so that we can use KnockoutJS
pattern in our application.We have added the link
https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js
2.The next part is "view" part.The entire HTML code is considered as view.Html element is bind with model.
3.Two HTML element First Name,Second Name binded with a attribute "data-bind" with two variable "firstName" and "SecondName".
4.ko.observable is a technique which keeps an eye on the value changes so that it can update the associated ViewModel data.
5.There is a function ,"computed" , which perform the required task , when the variable value has changed.
6.ko.applyBindings is concept of KnockoutJS for activation of binding.A binding context is an object that holds data that you can reference from your bindings.
The KnockoutJS has three core features
- Observables and dependency tracking
- Declarative bindings
- Templating
- Observables and dependency tracking
- Declarative bindings
- Templating
No comments:
Post a Comment