Introduction to KnockOut.Js
Knockout is a JavaScript library which helps in the creation of rich web UIs. There are many emerging JavaScript libraries off late like angular, backbone etc. I would take an opportunity to explain the concept and topic my way.
Introduction to KnockOut.JS
As I have mentioned in my Summary Section Knockout.Js is a JavaScript library which helps in the creation of rich web UIs. I came to know about this Scripting language in one the interviews that i have been taking for my organization. I have developed interest on this scripting language and started using the same in the application. It is very interesting and the beauty of this is you don't even need any editor for developing this. You can just use your notepad and develop the applications. Other interesting features of this framework is You don't have to worry about which DOM elements need to be changed/added/removed - the framework can take care of synchronizing things for you. Also Many of the most modern web-based UIs have gone beyond traditional Ajax and have become single page applications(SPA's). KnockOut.Js helps you to build SPA very easily.
Knockout.js uses the Model-View-ViewModel (MVVM) pattern. As most of you might already know that MVVM is a quite popular model which is used in WPF/Silverlight applications because of advantage that it provides the best separation of concerns, View is in charge of the visual representation while the non-visual ViewModel is in charge of all of the interactions with the rest of the software including the Model, the Services and the rest of the ViewModels. From now on I will simplify KnockOut.Js with an acronym term KO.
Why KO?
When I started reading and working through KO this is the question I got as we have many other JS libraries like JQuery etc. why should we go for KO?
Here are the reasons for using KO
• As with other JavaScript library it works with any server or client-side technology but major advantage is it is compact
• Also with minimal changes it can be added on top of your existing web application
• Supported on majority of browsers and easily pluggable on new browsers and platforms.
Can we use KO with Jquery?
First when I looked at KO I got a question is KO a replacement for jQuery? But it is not. KO will help us in binding the data and Data sets and allows to manipulate then easily with arrays etc. whereas JQuery helps us to manipulate elements and event handlers in a web page. In Fact we can combine JQuery with KO and use them in the same web page.
How to use KO?
To use KO first you need to download the Latest KnockOUT.JS from the site Download KO
Alternatively you can install it from NuGet Packages of your Visual studio.
I will start with a very simple example of displaying First name and Last name of a person and then go into the details of how the code works.
As I have mentioned KO follows MVVM pattern the way you code it also in the same way.
For the UI / View
p> First name: input data-bind="value: firstName" /> p>
p> Last name: input data-bind="value: lastName" /> p>
p> Full Name: span data-bind="text: fullName">/span> /p>
For the View Model following is the code sample
var ViewModel = function(first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel("Padmasri", "Vemuri"));
Note:As the html is parsing i had removed the<> for P and Input but while you are using you need to include the html tags and read it
For the KnockOut to be recognized you need to give the link as shown below for the correct version
script type='text/javascript' src='~/Scripts/knockout-3.0.0.js'>Ko.ApplyBindings Sets up bindings within the specified root element using the specified the model. this is where Model binding to the view model happens and this is important part of KO.
To give more details on KO, KO is built with three core features named below.
1) Dependency tracking through Observables - As the name suggestive Dependency tracking allows you to notify the listeners what are the changes that have happened without worrying about event handlers as in other scripting languages.It is done through Observables which are properties that will automatically issue notifications whenever their value changes.
In the above example firstName and lastName properties are observable and they are bound using ko.observable in ViewModel.
2) Declarative Bindings - To give a simple definition these are helpful to connect parts of your UI to your data model. I am giving a table below for the existing Bindings that are available. We can use custom binding as well for complex UI. This information is avaliable in the KnockOut site but i represented it in a simple form.
in the above example First name and last name are examples of declarative binding from view model using the syntax input data-bind="value: firstName" Type of Binding Purpose and Using it in your code Controlling text and appearance visible The visible binding causes the associated DOM element to become hidden or visible according to the value you pass to the binding.
div data-bind="visible: shouldShowMessage">This message seen only when "shouldShowMessage" holds a true value./div text The text binding causes the associated DOM element to display the text value of your parameter.div data-bind="text: message">/div> html
The html binding causes the associated DOM element to display the HTML specified by your parameter. div data-bind="html: details">
Css The css binding adds or removes one or more named CSS classes to the associated DOM element. div data-bind="css: { required: isRequired }">Name/div> style The style binding adds or removes one or more style values to the associated DOM element.
Note: you might have got a doubt that what is the Difference between style and css as i got. If you don't want to apply an explicit style value but instead want to assign a CSS class then we use Css div data-bind="style: { Color: "Black"}">Name Attr The attr binding provides a generic way to set the value of any attribute for the associated DOM element. div data-bind="attr: { desc: Description, id: itemId }">data Working with Form Fields Click The click binding executes a handler when the element is clicked. button data-bind="click: Submit">Click Me! /button> Event The event binding adds handlers to the element for the specified events. div data-bind="event: { mouseover: showHelp }">Bring your Mouse here Submit The submit binding allows you to execute a handler when a form is submitted. form data-bind="submit: saveData">…/form> Value The value binding enables two-way binding of the field's value to a view model value. input data-bind="value: name" /> Enable The enable binding controls whether the form element is enabled passed on the passed value. input data-bind="enable: isEditable, value: name" Disable
The disable binding provides the same functionality as the enable binding, but uses the opposite of the passed value. input data-bind="disable: isReadOnly, value: name" Hasfocus The disable binding provides the same functionality as the enable binding, but uses the opposite of the passed value. input data-bind="disable: isReadOnly, value: name" /> checked The checked binding links a checkable form control. It is mainly used with Checkbox/Radio button type of controls.
input type="checkbox" data-bind="checked: wantsSpam" Options The options binding controls what options should appear in a drop-down list or multi-select list. This binding cannot be used with anything other than select> elements. selectedOptions The selectedOptions binding controls which elements in a multi-select list are currently selected. This is intended to be used in conjunction with a select> element and the options binding. uniqueName
The uniqueName binding ensures that the associated DOM element has a nonempty name attribute. If the DOM element did not have a name attribute, this binding gives it one and sets it to some unique string value.
input data-bind="value: someModelProperty, uniqueName: true" Control Flow foreach The foreach binding helps for each entry in an array, and binds each copy of that markup to the corresponding array item. This is useful for rendering lists or tables. If I have list of people and I want to display Firstname and LastName in a table following is the example of Foreach binding. tbody data-bind="foreach: people">tr>td data-bind="text: firstName">td>td data-bind="text: lastName">td>tr>tbody> if The if binding causes a section of markup to appear in your document, only if a specified expression evaluates to true.label>input type="checkbox" data-bind="checked: displayMessage" Display message label>div data-bind="if: displayMessage">Here is a message. div> ifNot The ifNot binding is exactly reverse of if binding. with> The with binding creates a new binding context, so that descendant elements are bound in the context of a specified object.We can arbitrarily nest with bindings along with the other control-flow bindings such as if and foreach. /
Note:As the html is parsing i had removed the<> for Div but while you are using you need to include the html tags and read it.
3) Templates -
Templates are a simple and convenient way to build sophisticated UI structures with repeating or nested blocks. KO supports two types of templates Native templating and String-based templating.
Following are the wonderful sites which will help you as they did for me for learning KO
1) Official KO Documentation To access Click here
2) For practicing the examples of KO online you can use Jsfiddle
3) If we don't want to download the Library then we can sirectly reference the CDN sites for KO. you can find out the links to CDN in this site .