- Knockout is a JavaScript Library
- Which helps the creation of rich, desktop-like web UIs
- It simplifies user interactions and makes interfaces fully responsive to any data source changes
- Knockout provides a simple two-way binding mechanism to link a data model to an UI,
- Thus making synchronization between them a breeze
What are the Key Concepts of Knockout ?
1. Declarative Bindings
- These allow you to connect parts of your UI to your data model in a simple and convenient way
- With declarative bindings even if you change the DOM all bound pieces stay connected
- You can bind data to a DOM by simply including a data-bind attribute to any DOM element
2. Automatic UI Refresh
3. Dependency Tracking
- Every time when your model data has changed all parts associated with it automatically being updated
- No need to worry about adding event handlers and listeners
- All that extra work is performed internally by Knockout and observables,
- Which notify listeners when underlying values have changed
4. Templating
- when your application becomes more complex and you need a way to display a rich structure of view model data,thus keeping your code simple
- Knockout has a native, built-in template engine which you can use right away
- But if you want, a third-party template engine, like jquery.tmpl or Underscore, also can be used
More Features of Knockout
How to Download Knockout ?
Step 3
How to work with Knockout ?
1. You have to add a reference to the "knockout-2.2.0.js" File which you downloaded
2. Then You have to add Reference to above file inside your master file
i.e. Inside \Views\Shared\_Layout.cshtml
<script src="@Url.Content("~/Scripts/knockout-2.2.0.js")" type="text/javascript"></script>
That's it.Your done.
Lets try with some basic capabilities of Knockout
- ASP.Net MVC 3 and Visual Studio 2010 has been used
- ASP.Net MVC 3 and Visual Studio 2010 has been used
CASE 1 :
- For that you can use data-bind attributes
View's Code
<!-- This is a View - HTML markup that defines the
appearance of your UI -->
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<script type="text/javascript">
//This is a
simple Viewmodel
//JavaScript
that defines the data and behavior of your UI
function
AppViewModel() {
this.firstName
= "Sampath";
this.lastName
= "Lokuge";
}
//Activates
knockout.js
ko.applyBindings(new
AppViewModel());
</script>
CASE 2 : How to Make the data Editable (Dynamic Data) ?
- That's why Knockout has a concept of observables
- These are properties that automatically will issue notifications whenever their value changes
i.e.
- Not only that the underlying ViewModel data is being updated when you edit ,
- But that all associated UI is updating in Sync with it too
View's Code
<!-- This is a View - HTML markup that defines the
appearance of your UI -->
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<p>First name:<input data-bind="value: firstName" /></p>
<p>Last name:<input data-bind="value: lastName" /></p>
Javascript Code
<script type="text/javascript">
//This is a
simple Viewmodel
//JavaScript
that defines the data and behavior of your UI
function
AppViewModel() {
this.firstName
= ko.observable();
this.lastName
= ko.observable();
}
//Activates
knockout.js
ko.applyBindings(new
AppViewModel());
</script>
Output
CASE 3 : How to Define Computed Values ?
- To handle this, Knockout has a concept of Computed Properties
- These are observable (i.e., they notify on change)
- And they are computed based on the values of other observables
View's Code
<!-- This is a View - HTML markup that defines the
appearance of your UI -->
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<p>First name:<input data-bind="value: firstName" /></p>
<p>Last name:<input data-bind="value: lastName" /></p>
<p>Full name: <strong data-bind="text: fullName"></strong></p>
<script type="text/javascript">
//This is a
simple Viewmodel
//JavaScript
that defines the data and behavior of your UI
function
AppViewModel() {
var
self = this;
self.firstName = ko.observable();
self.lastName = ko.observable();
self.fullName = ko.computed(function () {
return
self.firstName() + " " +
self.lastName();
});
}
//Activates
knockout.js
ko.applyBindings(new
AppViewModel());
</script>
Output
- Need to add a capitalizeLastName function to the viewmodel
- To Read or Write an observable's value, you have to call it as a function
View's Code
<!-- This is a View - HTML markup that defines the
appearance of your UI -->
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<p>First name:<input data-bind="value: firstName" /></p>
<p>Last name:<input data-bind="value: lastName" /></p>
<p>Full name: <strong data-bind="text: fullName"></strong></p>
<button data-bind="click: capitalizeLastName"> Go CAPS </button>
<script type="text/javascript">
//This is a simple Viewmodel
//JavaScript that defines the data and behavior of your UI
function AppViewModel() {
var self = this;
self.firstName = ko.observable();
self.lastName = ko.observable();
self.fullName = ko.computed(function () {
return self.firstName() + " " + self.lastName();
});
self.capitalizeLastName = function () {
var currentVal = self.lastName();//Read the current value
self.lastName(currentVal.toUpperCase());//Write back a modified value
};
}
//Activates
knockout.js
ko.applyBindings(new
AppViewModel());
</script>
Output
Small discussion about Knockout on stackoverflow, Which I have involved
What has Said Creator of Knockout about This Article ?
Conclusion
- This is a very basic example, but it illustrates some of the key points of Knockout
- You've got a clean, object-oriented representation of your UI's data and behaviors (your viewmodel)
- Separately, you've got a declarative representation of how it should be displayed visibly (your view)
- You can implement arbitrarily sophisticated behaviors just by updating the viewmodel object
- You don't have to worry about which DOM elements need to be changed,added or removed ,
- The framework can take care of synchronizing things for you
I hope this helps to You.Comments and feedback greatly appreciated.
If you feel it was a good article,Give me a +1.Thank You.
Very good article!
ReplyDelete-Claudio Enrique Gonzalez Vera-
Hi Claudio,
DeleteThanks for your feedback.Do keep in touch.
Knockout is a very powerful javascript library that allows you to bind the user-interface part of a web-page to behind the scenes data. The UI will automatically be updated to reflect changes to that data.
ReplyDeleteYou set a reference to the Knockout libraries, then write a small amount of your own javascript to create a view model. In the mark-up for the page you reference this view model and use the data-bindings exposed by Knockout to connect the mark-up on the page to the data inside your view model.
I'm using this myself at the moment, it's made some very clever user-interface stuff very easy to implement, I'm very impressed. We're using it along with jquery to get JSON data from restful WCF web-services, and also to post JSON data back to those webservices.
-Stephen Malbon-
Hi Stephen,
DeleteThanks for your additional information.
nice article, please come with more on knockout
ReplyDeleteHi Suren,
DeleteYes sure.I will do more posts about knockout.
Thanks for your feedback.
Sampath its really new for me, also I'm searching this things. thanks for sharing with us. really good Demo machan.
ReplyDeleteHi Mohammed,
DeleteGlad to hear that it helped!.
Thanks for your feedback
Thanks Sampath.
ReplyDeleteContinue to do so.
Regards.
Dasun
Hi Dasun,
DeleteThanks for your comment.
Do Keep in Touch.
Great job.
ReplyDeleteHi Dasun,
DeleteThanks for appreciation.
Do keep in touch.
Nice. Kick start... I believe every one can easily understand this article..... thanks to author.
ReplyDeleteHi Mukesh,
DeleteGlad to hear that it helped!.
Thanks for your feedback.
Nice article and great job.
ReplyDeleteRegards
Syam Prasad
Hi Shyam,
DeleteThanks for your appreciation.
Do keep in touch.
ok, Thanks for information...
ReplyDelete-SANJAY YADAV -
Hi SANJAY,
DeleteThanks for your comment.
It's a nice article. I just touch it. I want to know whether we can use this with Asp.net(without MVC) and I am not clear how is it working, is it like Ajax with partial postback? I am reading more information of this, your comments are highly appreciated.
ReplyDeleteThanks,
Randima
Hi randimae,
DeleteYour Q 1: whether we can use this with Asp.net(without MVC)?
Answer : YES you can use knockout with any type of server side technology,because knockout is purely client side.
Check below link for "Using Knockout in your ASP.NET applications" : http://www.codeproject.com/Articles/153735/Using-KnockoutJS-in-your-ASP-NET-applications
Your Q 2 : Is it like Ajax with partial post-back ?
Answer : Yes It does Asynchronous call (or partial post-back).With ASP.Net webforms, you can simply response.write the json string to the client. While doing postbacks from the client, you can use the jquery $.postJSON and then setup params that will tell you what kind of operation the post is for, and then you can handle things accordingly on the server side's postback event, extracting information from Request.Form or Request.Querystring.
I hope this will help to you.
I recently used KnockoutJS in one of my projects and it basically lets you create a client-side model that is always synchronized with your html elements. In my project, it allowed me to create an application that had a lot of calculated fields. When you change the value in an input element, it automatically updates the model, all on the client. It makes the app more responsive and no server side processing needed. Excellent for building apps with lots of calculated fields.
ReplyDelete-Ray Cacciatore-
Hi Ray,
DeleteThanks a lot for coming with practical experience.It's very helpful.
It also simulates with silverlight MVVM pattern.
ReplyDelete-Rupesh Sah-
Hi Rupesh,
DeleteThanks for useful adding.
Nice.
ReplyDelete-Humair Memon-
Hi Humair,
DeleteThanks for your feedback.
Do keep in touch.
Like this.
ReplyDelete-Dhirendra Patil-
Hi Dhirendra,
DeleteThanks for your feedback.
If you've never heard of MVVM (Model - View - ViewModel), look it up. KnockoutJS allows you to set up a MVVM type pattern in your client side code. Your HTML is the View, the Model is typically data that lives on the server, and is passed down to the client either as its rendered to the users browser, or via an AJAX call, and the ViewModel is a class that you define in client side code (javascript or TypeScript) that controls the interaction of your view with the bound model data. What makes this nice is that binding with controls and your data is automatically two-way, and because the logic for your page lives in the ViewModel class, it provides a really clean separation of concerns; your view only cares about shaping data, but not where it gets it, and your ViewModel doesn't care about the UI; it simply knows that it needs to look for SOMETHING that will take its data
ReplyDelete-Jamie Nordmeyer-
Hi Jamie,
DeleteThanks a lot for very useful information.
Do keep in touch.
Great Article brother
ReplyDeleteHi Prashan,
DeleteThanks for your appreciation.
Do keep in touch.
Hi Sampath...gooo stuff...we r planning to use Knockout.js in one of ur proj. implementations..pretty interesting and maintainability looks easier :)
ReplyDeleteHi Abheesh,
DeleteYes.You can go ahead with Knockout.Good luck.
Thanks for your feedback.
hi,
ReplyDeleteplease get Loading and saving data knockout lesson ASAP......
thanks..
-Aruna Madushan-
Hi Aruna,
DeleteOK sure.I will do and let you know.
Thanks for your feedback.
Hello There. I found your blog using msn. This is a really
ReplyDeletewell written article. I'll make sure to bookmark it and come back to read more of your useful information. Thanks for the post. I'll certainly comeback.
Hi,
DeleteThanks for your feedback.
Do keep in touch.