This document provides an overview of Knockout JS, a JavaScript library for building user interfaces. It begins with introductions to Knockout JS and the Model-View-ViewModel (MVVM) pattern. The document then covers key Knockout concepts like observables, computed properties, subscribers, and bindings. It provides examples of how to use these features to create two-way data bindings between a view model and HTML. Overall, the document serves as an introduction for learning how to use Knockout JS to build responsive and dynamic user interfaces.
2. About Me
•I am Ravinder Mahajan, working as a web developer since
beginning of my career.
•I am microsoft certified HTML5 with JavaScript and CSS3
solution provider.
• I love to explore about the latest technologies/libraries.
•In free time I like to travel to different places.
http://www.linkedin.com/pub/ravinder-mahajan/23/508/668
3. Agenda for this session
• What is knockout js?
• What is MVVM?
• Why to use Knockout js?
• What are observables?
• What are computed properties?
• What are subscribers?
• What are Bindings in knockout?
• Pros and Cons of knockout
Few Examples at the end to demonstrate the same!!!
4. What is knockout?
• Knockout is a JavaScript library built mainly
to provide two way binding between HTML
and Data(View model) and gives us a
responsive display.
• Two way binding
HTML In sync ViewModel
5. Agenda for this session
✓ What is knockout js?
✓ What is MVVM?
✓ Why to use Knockout js?
✓ What are observables?
✓ What are computed properties?
✓ What are subscribers?
✓ What are Bindings in knockout?
✓ Pros and Cons of knockout
Few Examples at the end to demonstrate the same!!!
6. What is MVVM?
MVVM is a pattern which helps us achieve Two way binding
between our HTML page and Data.
• Model: The model represents the actual data and/or
information we are dealing with
• View: The view is something that end user really
interacts with ie the HTML content
• ViewModel: The viewmodel may expose the model
directly, or properties related to the model, for data-
binding in a formatted/Refined or presentable form.
Ex: let us suppose that our Model Contains a lot of detail
about employees however at the UI we only want to
display Name And Age, this is something what is achieved
by ViewModel
8. Agenda for this session
✓What is knockout js?
✓What is MVVM?
✓Why to use Knockout js?
✓What are observables?
✓What are computed properties?
✓What are subscribers?
✓What are Bindings in knockout?
Few Examples at the end to demonstrate the same!!!
9. Why to use knockout
• Declarative Binding: Binding View Models’ properties to HTML is
very easy
Eg: <span data-bind="text: myProperty"></span>
• Automatic Dom refresh: Every time a property changes in View
Model, its associated Dom is automatically refreshed but not the
entire Page
• Dependency Tracking: If a property is dependent on other property
then knockout can easily detect that and can perform further
operations.
• Templating: Knockout provides you with its own templating engine
which is quite fast, however we can also use any of our templating
engines.
Note: Knockout is very light weight and does not have any
dependency on any other js library.
10. Agenda for this session
✓ What is knockout js?
✓ What is MVVM?
✓ Why to use Knockout ?
✓ What are observables?
✓ What are computed properties?
✓ What are subscribers?
✓ What are Bindings in knockout?
✓ What are custom Bindings?
Few Examples at the end to demonstrate the same!!!
11. What are observables?
• Observable are knockout properties which holds the Model
properties needed to bind the data to the UI and internally is
responsible for Two way binding.
Example
function MyViewModel(){
this.firstName: ko.observable(‘Ravinder’),
this.lastName: ko.observable(‘Mahajan’)
};
ko.applyBindings(new MyViewModel(),$(‘#personName’));
<span id=‘personName’ data-bind=“text:firstName”> // Ravinder
http://jsfiddle.net/ravindermahajan890/DM67E/
12. Agenda for this session
✓ What is knockout js?
✓ What is MVVM?
✓ Why to use Knockout ?
✓ What are observables?
✓ What are computed properties?
✓ What are subscribers?
✓ What are Bindings in knockout?
✓ What are custom Bindings?
Few Examples at the end to demonstrate the same!!!
13. What are computed Observables?
• computed observables are functions that are dependent on
one or more other observables, and will automatically update
whenever any of these dependencies change.
Example:
function MyViewModel(){
this.firstName: ko.observable(‘Ravi’);
this.lastName: ko.observable(‘Jain’);
this.fullName=ko.computed(function(){
return this.firstName()+ this.lastName();
},this);
};
ko.applyBindings(new MyViewModel(),$(‘#personName’));
<span id=‘personName’ data-bind=“text:fullName”> // Ravi Jain
14. Case1:
First Name:Ravinder
Last Name:Mahajan
Full Name:Ravinder Mahajan
Now if we edit first and Last Name:
Case2:
First Name: Ankit
Last Name: Kumar
Full Name: Ankit Kumar
http://jsfiddle.net/ravindermahajan890/J8Ymw/
Note: Full name always detect the change in First Name and Last
Name by subscribing to them internally and is computed every
time.
15. Agenda for this session
✓ What is knockout js?
✓ What is MVVM?
✓ Why to use Knockout ?
✓ What are observables?
✓ What are computed properties?
✓ What are subscribers?
✓ What are Bindings in knockout?
✓ What are custom Bindings?
Few Examples at the end to demonstrate the same!!!
16. What are subscribers?
• Subscriptions are registered to notify any change in the
subscribed properties.
Example 1:
var myViewModel= new MyViewModel();
myViewModel.personName.subscribe(function(newValue) {
alert(“New value is " + newValue);
});
Example 2:
myViewModel.personName.subscribe(function(newValue) {
alert(“New value is " + newValue);
},this,”beforeChange”);
http://jsfiddle.net/ravindermahajan890/qYhTw/3/
17. Agenda for this session
✓What is knockout js?
✓What is MVVM?
✓Why to use Knockout ?
✓What are observables?
✓What are computed properties?
✓What are subscribers?
✓What are Bindings in knockout?
✓What are custom Bindings?
Few Examples at the end to demonstrate the same!!!
18. What are Bindings in knockout?
Binding is a phenomenon where in we actually bind
the data present in ViewModels to our HTML page
using some pre-defined keyword(s) well understood
by Knockout
Different types of Binding are available:
1. Text , HTML and appearance Bindings
2. Control flow Bindings
3. Form fields Bindings
4. Custom Binding(To be covered Later)
19. 1) Text , HTML and appearance Bindings
• visible binding: Visible binding causes the Dom Element to
switch is visiblity property on the basis of associated Knockout
Property.
Example:
<div data-bind="visible: visiblePropertyName">
You will see this message only when " visiblePropertyName "
holds a true value.
</div>
var viewModel = {
visiblePropertyName : ko.observable(true)
};
viewModel. visiblePropertyName (false);//This div will not be
visible anymore
http://jsfiddle.net/ravindermahajan890/2aYXj/
20. • Text binding: Text binding causes the associated DOM
element to display the text value of associated property. We
can use it with almost all the elements.
Example 1:
<span data-bind="text: myMessage , visible:myMessage()!=null
"></span>
var viewModel = {
myMessage: ko.observable(null) ,
count:ko.observable(10)
};
viewModel.myMessage(“Welcome to the world of knockout!");
Text Binding
22. HTML Binding
• HTML binding first converts the string into its corresponding
HTML value and then binds the data to it.
• The HTML binding causes the associated DOM element to
display the HTML specified by your parameter.
Example:
<div data-bind="html: details"></div>
var viewModel = {
details: ko.observable()
};
viewModel.details("<em>welcome to <i>Synerzip</i></em>");
Output:
“welcome to Synerzip”
23. Note: It is always preferred to use text binding as it removes
the problem of script inection or if we are using HTML binding,
make sure we encode the text first.
http://jsfiddle.net/ravindermahajan890/8XW43/
24. CSS Binding
The css binding adds or removes one or more named CSS classes
to the associated DOM element.
Example 1:
<div data-bind="css: { profitWarning: currentProfit() < 0 }">
Profit Information
</div>
In this example if the currentProfit() evaluates to less than 0 then
the profit warning css would be applied to the Div.
CSS Expression
25. Example 2:
<div data-bind="css: { profitWarning: currentProfit() < 0, major
highlight: isSevere }">
This example explains that how can we switch between css
classes on the basis of our conditions.
http://jsfiddle.net/ravindermahajan890/k7ys4/1/
26. Style Binding
The style binding adds or removes one or more style values to
the associated DOM element
Example:
<div data-bind="style: { color: age() < 0 ? 'red' : 'black' }">
Profit Information
</div>
var viewModel = {
age: ko.observable(15)
};
viewModel.age(-50);
In this example the color value would change its property on the
basis of the age() condition.
27. Attr Binding
The attr binding ia a way to set the value of any attribute for
the associated DOM element. It is useful, when we want to
assign any attribute on the basis of our viewModels( mainly
“src” of an img tag, or the “href” of a link based on values in
your view model, title of any element)
<a data-bind="attr: { href: url, title: details }">
Synerzip
</a>
var viewModel = {
url: ko.observable(“synerzip.html"),
details: ko.observable(“Welcome to Synerzip")
};
28. 2) Control Flow Bindings
Control Flow Bindings are the bindings which control the flow
of application
Different types of Control Flow Binding are:
• Foreach Binding
• If Binding
• Ifnot Binding
• With Binding
Note: ”ifnot” binding is as good as negated if binding so we will
not touch on ifnot binding
29. foreach Binding
The foreach binding is generally used to render list or tables
where in the value/Properties is an observable array.
Example:
<div data-bind="foreach: people">
<div data-bind="text: name"></div>
</div>
var viewModel = {
people: ko.observableArray([{ name: 'Bert' },{ name:
'Charles' }, { name: 'Denise' }]) };
Output:
Bert
Charles
Denise
http://jsfiddle.net/ravindermahajan890/mC73V/1/
30. If Binding
The if binding causes your HTML element in your document only
if a specified expression evaluates to true/Non null object.
Example 1:
<div data-bind="if: displayMessage">
<span>My content<span>
</div>
var viewModel={
displayMessage: ko.observable(false)
};
In the above example the div would not take any space in the
DOM and would not be rendered
31. Example 2:
<div data-bind="if: displayMessage">
<span>My content<span>
</div>
var viewModel={
displayMessage: ko.observable(true)
};
I would be able to see My content on the page as the
displayMessage property evaluates to true
http://jsfiddle.net/ravindermahajan890/KAAxD/
32. Note: If binding is somewhat similar to visible binding however
the difference is that with “visible” binding the HTML always
remains in the Dom and which at time becomes overhead but in
the case of “if” binding the element is rendered when the
condition evaluates to true and applies bindings to its
descendants only when the “if” binding evaluates to true.
33. with binding
“The with binding creates a new binding context, so that
descendant elements are bound in the context of a specified
object”
Ex1:
<div data-bind="with: name“>
<span data-bind="text: firstName"> </span>//name.firstName
<span data-bind="text: lastName"> </span>//name.lastName
</div>
var viewModel={
name: {
firstName: ’Ravinder’,
lastName: ‘Mahajan’
}
});
http://jsfiddle.net/ravindermahajan890/drF9L/
34. Container less Binding
In Container less binding the binding can be easily achieved
without using a container element.
Example 1:
<!-- ko foreach: people -->
<div data-bind="text: name"></div>
<!-- /ko -->
Example 2:
<!-- ko if: displayMessage -->
<span>My content<span>
<!-- /ko -->
35. Example 3:
<!-- ko with: name>
<span data-bind="text: firstName"> </span>//name.firstName
<span data-bind="text: lastName"> </span>//name.lastName
<!-- /ko -->
http://jsfiddle.net/ravindermahajan890/m2uVt/
36. 3) Form Fields Binding
These are the bindings which are used while
working with Form fields.
Different types of Form field bindings are:
• "click" binding
• “event” binding
• “submit” binding
• “enable” binding
• “value” binding
• “checked” binding
• “options” binding
• "selectedOptions" binding
37. "click" binding
• The click binding adds an event handler so that your chosen
JavaScript function will be invoked when the associated DOM
element is clicked
Example 1:
<div>You've clicked
<span data-bind="text: numberOfClicks"></span> times
<button data-bind="click: incrementClickCounter">Click me</button>
</div>
var viewModel = {
numberOfClicks : ko.observable(),
incrementClickCounter : function(data,event) {
var previousCount = this.numberOfClicks();
this.numberOfClicks(previousCount + 1);
}};
In this example clicking on the button would increment the
this.numberOfClicks by1.
38. “submit” binding
Submit binding is very much similar to click binding on button,
submit binding prevents the default submit action and will call
your method instead.
However, submit has the advantage that it also captures
alternative ways to submit the form, such as pressing
the enter key while typing into a text box.
http://jsfiddle.net/ravindermahajan890/qWg82/2/
39. “enable” binding
• The enable binding causes the Dom element to be
enabled or disabled on the basis of observable
property
Example 1:
<input type=“text” data-bind='enable: name()!=‘null’,value:
name">
click to enable
</input>
var viewModel = {
this.name: ko.observable(null)
};
http://jsfiddle.net/ravindermahajan890/qWg82/2/
40. “value” binding
• Value binding binds your elements present in your DOM to
the properties present in view model.
• They are mainly used with form fields such as Input , Select.
• Whenever user changes any value to these form fields then
the value is also updated in view model.
Note: If you’re working with checkboxes or radio buttons,
use the checked binding to read and write your element’s
checked state, not the value binding.
42. Example 2: DropDown
<p>
Select a name:
<select data-bind="options: countries,
optionsCaption: 'Choose one
value: selectedName>
</select>
</p>
var viewModel = {
names: ko.observableArray(*‘Ravinder', ‘Amit',
‘Kunal‘,’nachiket’+),
selectedName: ko.observable()
};
http://jsfiddle.net/ravindermahajan890/tbCY8/3/
43. “checked” binding
• Checked binding binds your checkbox/Radio button present
in your DOM to the properties present in view model.
• Whenever the checkbox/Radio Button is checked the
associated observable becomes true.
Ex1: Checkbox
<input type="checkbox" data-bind="checked: name" />
<input type="checkbox" data-bind="checked: age" />
var viewModel = {
name : ko.observable(true), age: ko.observable(false)
};
In this example the property associated with the correspondoing
DOM element will decide the Checked value of checkbox.
http://jsfiddle.net/ravindermahajan890/Bkt58/
44. Example 2: checkboxes bound to an array
<div>Sports we like:
<div><input type="checkbox" value=“cricket" data-
bind="checked: sports" /> Cricket</div>
<div><input type="checkbox" value=“soccer" data-
bind="checked: sports" /> Soccer</div>
<div><input type="checkbox" value=“tennis" data-
bind="checked: sports" /> Tennis</div>
</div>
var viewModel = {
sports: ko.observableArray([" cricket "," soccer "])
};
In this example the check box with value cricket and soccer will
be checked by default.
http://jsfiddle.net/ravindermahajan890/NC7pY/
45. Example 3: Radio buttons
<div> Sports we like:
<div><input type=“radio" name=“sportsGroup” value=“cricket"
data-bind="checked: sports" /> Cricket</div>
<div><input type=“radio" name=“sportsGroup” value=“soccer"
data-bind="checked: sports" /> Soccer</div>
<div><input type=“radio" name=“sportsGroup” value=“tennis"
data-bind="checked: sports" /> Tennis</div>
</div>
var viewModel = {
sports: ko.observable(‘cricket’)
};
In this example the radio box with value cricket will be checked
by default.
Note: We cannot have the value for the radio buttton under
single name populated from an observable array.
46. “selectedOptions” binding
• This binding is used in case of multi-select lists and all the the
values currently selected are put in an observable array.
Example :
<p>
Select a name:
<select data-bind="options: names,
selectedOption:selectedName”,
size=“2“, multiple="true"</select>
</p>
var viewModel = {
names: *‘Ravinder', ‘Amit',‘Kunal‘,’nachiket’+,
selectedName: ko.observableArray()
};
http://jsfiddle.net/ravindermahajan890/v5AVU/
47. Agenda for this session
✓What is knockout js?
✓What is MVVM?
✓Why to use Knockout ?
✓What are observables?
✓What are computed properties?
✓What are subscribers?
✓What are Bindings in knockout?
✓Pros and Cons of knockout
Few Examples at the end to demonstrate the same!!!
48. Pros and Cons of knockout
Pros:
• Light and fast, only 41kb
• Declarative two-way binding
• It lets you manipulate the CSS from the HTMl itself on the
basis of observables.
• The amount of JavaScript code to write is very less
• No dependency on any other library.
Cons:
• Jquery templates are not completely supported
• It provides only two way binding and does not support
modern concepts like Hash based Routing
49. Agenda for this session
✓What is knockout js?
✓What is MVVM?
✓Why to use Knockout ?
✓What are observables?
✓What are computed properties?
✓What are subscribers?
✓What are Bindings in knockout?
✓ Pros and Cons of knockout
Few Examples at the end to demonstrate the same!!!