S I M P L I F Y D Y N A M I C J A V A S C R I P T U I S B Y
A P P L Y I N G T H E M O D E L- V I E W -
V I E W M O D E L ( M V V M )
Knockout.js
What is Knockout.js ?
 Knockout is a JavaScript library that helps us to
create rich, responsive and dynamic display with a
clean underlying data model.
 Any time you have sections of UI that update
dynamically (e.g., changing depending on the user’s
actions or when an external data source changes),
KO can help you implement it more simply and
maintainably.
MVVM
Key points
 Free, open source (MIT license)
 Pure JavaScript — works with any web framework
 Small & lightweight — 40kb minified
 ... reduces to 14kb when using HTTP compression
 No dependencies
 Supports all mainstream browsers
 IE 6+, Firefox 2+, Chrome, Opera, Safari (desktop/mobile)
 Fully documented
 API docs, live examples, and interactive tutorials included
Features it offers
 Declarative Bindings
 Easily associate DOM elements with model data using a concise, readable
syntax
 Automatic UI Refresh
 Whenever data model's state changes, UI updates automatically
 Dependency Tracking
 Implicitly set up chains of relationships between model data, to transform
and combine it
 Templating
 Quickly generate sophisticated, nested UIs as a function of your model data
jQuery/js Frameworks Knockout
 Basically a replacement for the
clunky, inconsistent DOM APIs
we had to put up with in the
past.
 A low-level way to manipulate
elements and event handlers in
a web page.
 Knockout provides a
complementary, high-level way
to link a data model to a UI.
Is it different from jQuery or any other javascript
framework?
Note: Both can be used in solution seamlessly.
Core Features
 Observables and dependency tracking
 Declarative bindings
 Templating
Let’s Bind
//Javascript Code
<script>
var myViewModel = {
personName: ‘Vivek',
personAge: 27
};
//Restrict the binding to this span only
ko.applyBindings(myViewModel, document.getElementById(‘name'));
</script>
//HTML Code
The name is <span id=“name” data-bind="text: personName"></span>
Observables
 Last example was the basic one as it was kind of one
way binding i.e. the ViewModel’s property will show
up in UI but if we want that on every change of
property in ViewModel the UI should also get
reflected then make it observable property:
var myViewModel = {
personName: ko.observable(Vivek'),
personAge: ko.observable(27)
};
Explicitly subscribing to observables
 In the last example if we want to listen the value
change of personName property:
myViewModel.personName.subscribe(function(newValue) {
alert("The person's new name is " + newValue);
});
 If you want to terminate the subscription:
var subscription = myViewModel.personName.subscribe(function(newValue) {
alert("The person's new name is " + newValue);
});
subscription.dispose(); // no longer want notifications
Computed Observables
function myViewModel() {
this.firstName = ko.observable(‘Johnny');
this.lastName = ko.observable(‘English');
}
 Here in above ViewModel if you want to show Full
name which you want it to be dynamic(observable)
i.e. full name changes with a change in first/last
name
function myViewModel() {
this.firstName = ko.observable(‘Johnny');
this.lastName = ko.observable(‘English');
this.fullName = ko.computed(function(){
return this.firstName() +” “+ this.lastName();
}, this);
}
//HTML Code
The name is <span data-bind="text: fullName"></span>
Bindings
 Types of binding available:
visible, text, html, css, style, attr
 “visible”
<div data-bind="visible: shouldShowMessage">
You will see this message only when "shouldShowMessage" holds a true value.
</div>
<script type="text/javascript">
var viewModel = {
shouldShowMessage: ko.observable(true) // Message initially visible
};
viewModel.shouldShowMessage(false); // ... now it's hidden
viewModel.shouldShowMessage(true); // ... now it's visible again
</script>
 “text”
Today's message is: <span data-bind="text: myMessage"></span>
<script type="text/javascript">
var viewModel = {
myMessage: ko.observable() // Initially blank
};
viewModel.myMessage("Hello, world!"); // Text appears
</script>
 “html”
<div data-bind=“html: details"></div>
<script type="text/javascript">
var viewModel = {
details: ko.observable() // Initially blank
};
viewModel.details("<em>For further details, view the report <a
href='report.html'>here</a>.</em>"); // HTML content appears
</script>
 “css”
<div data-bind="css: { error: limit() < 0 }">
Range Information
</div>
<script type="text/javascript">
var viewModel = {
limit: ko.observable(100) //say a valid range is 0-100
};
viewModel.limit(-10); // Causes the “error" class to be applied
</script>
 “style”
<div data-bind="style: { error: limit() < 0 ? ‘red’ :’black’}">
Range Information
</div>
<script type="text/javascript">
var viewModel = {
limit: ko.observable(100) //say a valid range is 0-100
};
viewModel.limit(-10); // Causes the DIV’s content to go red
</script>
 “attr”
<a data-bind="attr: { href: url, title: details }">
Report
</a>
<script type="text/javascript">
var viewModel = {
url: ko.observable("year-end.html"),
details: ko.observable("Report including final year-end statistics")
};
</script>
For custom attributes you can write:
<a data-bind="attr: { ‘custom-attribute’: customvValue}">
Report
</a>
Note: attribute here is enclosed in quotes.
Control Flow Statements
 “foreach”
 “if”
 “ifnot”
 “with”
 “foreach”
<table>
<thead>
<tr><th>First name</th><th>Last name</th></tr>
</thead>
<tbody data-bind="foreach: people">
<tr>
<td data-bind="text: firstName"></td>
<td data-bind="text: lastName"></td>
</tr>
</tbody>
</table>
</script>
function myViewModel() {
var self = this;
self.people = ko.observableArray([ //The change in the array will reflect in the UI
{ name: 'Bert' },
{ name: 'Charles' },
{ name: 'Denise' }
]);
}
ko.applyBindings(new myViewModel());
</script>
 “if”
<div data-bind="if: displayMessage">Message is being displayed.</div>
<script>
ko.applyBindings({
displayMessage: ko.observable(false)
});
</script>
 “ifnot”
<div data-bind="ifnot: displayMessage">Message is being displayed.</div>
<script>
ko.applyBindings({
displayMessage: ko.observable(false)
});
</script>
Note: similar to <div data-bind="if: !someProperty()">...</div>
 “with”
Creates a new binding context, so that descendant elements are bound in the context
of a specified object.
<h1 data-bind="text: city"> </h1>
<p data-bind="with: coords">
Latitude: <span data-bind="text: latitude"> </span>,
Longitude: <span data-bind="text: longitude"> </span>
</p>
<script type="text/javascript">
ko.applyBindings({
city: "London",
coords: {
latitude: 51.5001524,
longitude: -0.1262362
}
});
</script>
Form fields binding
 Click binding
 Event Binding
 Submit Binding
 Enable Binding
 Disable Binding
 Value Binding
 HasFocus Binding
 Checked Binding
 Options Binding
 SelectedOptions Binding
 The uniqueName binding
Template Binding
 Native templating: Uses HTML markup contained in the
body only. Built into knockout and doesn’t require any external library.
 String-based templating: Knockout passes the model
values to the external template engine and inject the resulting markup
back into our document. Similar to what we were doing it till now using
jQuery template. Other library being Underscore template engines.
<h2>Participants</h2>
Here are the participants:
<div data-bind="template: { name: 'person-template', data: buyer }"></div>
<div data-bind="template: { name: 'person-template', data: seller }"></div>
<script type="text/html" id="person-template">
<h3 data-bind="text: name"></h3>
<p>Credits: <span data-bind="text: credits"></span></p>
</script>
<script type="text/javascript">
function MyViewModel() {
this.buyer = { name: 'Franklin', credits: 250 };
this.seller = { name: 'Mario', credits: 5800 };
}
ko.applyBindings(new MyViewModel());
</script>
NativeTemplating
<h1>People</h1>
<div data-bind="template: 'peopleList'"></div>
<script type="text/html" id="peopleList">
{{each people}}
<p>
<b>${name}</b> is ${age} years old
</p>
{{/each}}
</script>
<script type="text/javascript">
var viewModel = {
people: ko.observableArray([
{ name: 'Rod', age: 123 },
{ name: 'Jane', age: 125 },
])
}
ko.applyBindings(viewModel);
</script>
String-based Templating
Click binding
 The click binding is one of the simplest binding and
is used to invoke a Javascript function associated
with a DOM element based on a click. This binding
works like event handler.
 This is most commonly used with elements
like button, input, and a, but actually works with any
visible DOM element.
Syntax
 click: <binding-function>
Click Binding
Parameters
 Main parameter
 The function you want to bind to the
element’s click event.
 You can reference any JavaScript function - it
doesn’t have to be a function on your view model.
You can reference a function on any object by
writing click: someObject.someFunction.
 Additional parameters
 None
$parent/$root:
 If you’re inside a nested binding context,
 for example if you’re inside a foreach or a with block,
but your handler function is on the root viewmodel
or some other parent context, you’ll need to use a
prefix such as $parent or $root to locate the handler
function.
Click Binding
<div data-bind="click: myDivHandler">
<button data-bind="click: myButtonHandler”>
Click me
</button>
</div>
Event Binding
 This binding is used to listen to specific DOM event
and call associated handler function based on it.
Syntax
 event: <{DOM-event: handler-function}>
Parameters
 Parameter is inclusive of a Javascript object which
contains DOM event which will be listened to and a
handler function which needs to be invoked based on
that event.
Has Foucs Binding
 This binding is used to manually set the focus of a
HTML DOM element through a ViewModel
property. This is also a two ways binding method.
When the element is focused from UI, Boolean value
of ViewModel property is also changed and vice
versa.
Submit Binding
 This binding is used to invoke a Javascript function
when the associated DOM element is submitted. This
binding is used mostly for formelements.
 The form is not actually submitted to server when
submit binding is used. KO prevents browsers
default action. If you want submit binding to work as
real submit element then just return true from your
handler function.
Selected Options Binding
 This binding is used to work with elements which are
selected currently in multi list select form control. This
binding can be used with option binding and <select>
form control only.
 When the user selects or de-selects an item in the multi-
select list, this adds or removes the corresponding value
to an array on your view model. Assueme if it is
an Observable array then items selected or de-selected
from UI are also updated in array in ViewModel thus
making it a two-way binding method.
Knockout Validation
 Include knockout.validation.JS file into the project.
 Use Extenders to implement the default validation.
//start using it! var myValue =
ko.observable().extend({ required: true });
//oooh complexity var myComplexValue =
ko.observable().extend({ required: true, minLength:
3, pattern: { message: 'Hey this doesnt match my
pattern', params: '^[A-Z0-9].$' } });
Knockout Validation
 Inbuilt Validation
 Required
 Min
 Max
 MinLength
 Digit
 Email
 Number
 Pattern
 Equal and not Equal
 Custom
Knockout JS Utility Functions
 ko.utils.parseJson
 ko.utils.arrayMap
function Item(name, category, price) {
this.name = ko.observable(name);
this.category = ko.observable(category);
this.price = ko.observable(price);
this.priceWithTax = ko.dependentObservable(function() {
return (this.price() * 1.05).toFixed(2); }, this); }
//do some basic mapping (without mapping plugin)
var mappedData = ko.utils.arrayMap(dataFromServer,
function(item) { return new Item(item.name, item.category,
item.price); });
Knockout JS Utility Functions
 ko.utils.arrayForEach
 Array functions (filtering,sorting,Searching)
 Ko.toJS()
 Ko.toJSON()
Custom bindings
 Creating custom bindings
You’re not limited to using the built-in bindings
like click, value, and so on — you can create your
own ones.
This is how to control how observables interact with
DOM elements, and gives you a lot of flexibility to
encapsulate sophisticated behaviors in an easy-to-
reuse way.
Custom Bindings
<div data-bind="yourBindingName: someValue"> </div>
Note: you don’t actually have to provide both init and update callbacks — you
can just provide one or the other if that’s all you need.
Custom binding
Custom Binding
Now you can use this binding as follows:

Knockoutjs

  • 1.
    S I MP L I F Y D Y N A M I C J A V A S C R I P T U I S B Y A P P L Y I N G T H E M O D E L- V I E W - V I E W M O D E L ( M V V M ) Knockout.js
  • 2.
    What is Knockout.js?  Knockout is a JavaScript library that helps us to create rich, responsive and dynamic display with a clean underlying data model.  Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.
  • 3.
  • 4.
    Key points  Free,open source (MIT license)  Pure JavaScript — works with any web framework  Small & lightweight — 40kb minified  ... reduces to 14kb when using HTTP compression  No dependencies  Supports all mainstream browsers  IE 6+, Firefox 2+, Chrome, Opera, Safari (desktop/mobile)  Fully documented  API docs, live examples, and interactive tutorials included
  • 5.
    Features it offers Declarative Bindings  Easily associate DOM elements with model data using a concise, readable syntax  Automatic UI Refresh  Whenever data model's state changes, UI updates automatically  Dependency Tracking  Implicitly set up chains of relationships between model data, to transform and combine it  Templating  Quickly generate sophisticated, nested UIs as a function of your model data
  • 6.
    jQuery/js Frameworks Knockout Basically a replacement for the clunky, inconsistent DOM APIs we had to put up with in the past.  A low-level way to manipulate elements and event handlers in a web page.  Knockout provides a complementary, high-level way to link a data model to a UI. Is it different from jQuery or any other javascript framework? Note: Both can be used in solution seamlessly.
  • 7.
    Core Features  Observablesand dependency tracking  Declarative bindings  Templating
  • 8.
    Let’s Bind //Javascript Code <script> varmyViewModel = { personName: ‘Vivek', personAge: 27 }; //Restrict the binding to this span only ko.applyBindings(myViewModel, document.getElementById(‘name')); </script> //HTML Code The name is <span id=“name” data-bind="text: personName"></span>
  • 9.
    Observables  Last examplewas the basic one as it was kind of one way binding i.e. the ViewModel’s property will show up in UI but if we want that on every change of property in ViewModel the UI should also get reflected then make it observable property: var myViewModel = { personName: ko.observable(Vivek'), personAge: ko.observable(27) };
  • 10.
    Explicitly subscribing toobservables  In the last example if we want to listen the value change of personName property: myViewModel.personName.subscribe(function(newValue) { alert("The person's new name is " + newValue); });  If you want to terminate the subscription: var subscription = myViewModel.personName.subscribe(function(newValue) { alert("The person's new name is " + newValue); }); subscription.dispose(); // no longer want notifications
  • 11.
    Computed Observables function myViewModel(){ this.firstName = ko.observable(‘Johnny'); this.lastName = ko.observable(‘English'); }  Here in above ViewModel if you want to show Full name which you want it to be dynamic(observable) i.e. full name changes with a change in first/last name function myViewModel() { this.firstName = ko.observable(‘Johnny'); this.lastName = ko.observable(‘English'); this.fullName = ko.computed(function(){ return this.firstName() +” “+ this.lastName(); }, this); } //HTML Code The name is <span data-bind="text: fullName"></span>
  • 12.
    Bindings  Types ofbinding available: visible, text, html, css, style, attr  “visible” <div data-bind="visible: shouldShowMessage"> You will see this message only when "shouldShowMessage" holds a true value. </div> <script type="text/javascript"> var viewModel = { shouldShowMessage: ko.observable(true) // Message initially visible }; viewModel.shouldShowMessage(false); // ... now it's hidden viewModel.shouldShowMessage(true); // ... now it's visible again </script>
  • 13.
     “text” Today's messageis: <span data-bind="text: myMessage"></span> <script type="text/javascript"> var viewModel = { myMessage: ko.observable() // Initially blank }; viewModel.myMessage("Hello, world!"); // Text appears </script>  “html” <div data-bind=“html: details"></div> <script type="text/javascript"> var viewModel = { details: ko.observable() // Initially blank }; viewModel.details("<em>For further details, view the report <a href='report.html'>here</a>.</em>"); // HTML content appears </script>
  • 14.
     “css” <div data-bind="css:{ error: limit() < 0 }"> Range Information </div> <script type="text/javascript"> var viewModel = { limit: ko.observable(100) //say a valid range is 0-100 }; viewModel.limit(-10); // Causes the “error" class to be applied </script>  “style” <div data-bind="style: { error: limit() < 0 ? ‘red’ :’black’}"> Range Information </div> <script type="text/javascript"> var viewModel = { limit: ko.observable(100) //say a valid range is 0-100 }; viewModel.limit(-10); // Causes the DIV’s content to go red </script>
  • 15.
     “attr” <a data-bind="attr:{ href: url, title: details }"> Report </a> <script type="text/javascript"> var viewModel = { url: ko.observable("year-end.html"), details: ko.observable("Report including final year-end statistics") }; </script> For custom attributes you can write: <a data-bind="attr: { ‘custom-attribute’: customvValue}"> Report </a> Note: attribute here is enclosed in quotes.
  • 16.
    Control Flow Statements “foreach”  “if”  “ifnot”  “with”
  • 17.
     “foreach” <table> <thead> <tr><th>First name</th><th>Lastname</th></tr> </thead> <tbody data-bind="foreach: people"> <tr> <td data-bind="text: firstName"></td> <td data-bind="text: lastName"></td> </tr> </tbody> </table>
  • 18.
    </script> function myViewModel() { varself = this; self.people = ko.observableArray([ //The change in the array will reflect in the UI { name: 'Bert' }, { name: 'Charles' }, { name: 'Denise' } ]); } ko.applyBindings(new myViewModel()); </script>
  • 19.
     “if” <div data-bind="if:displayMessage">Message is being displayed.</div> <script> ko.applyBindings({ displayMessage: ko.observable(false) }); </script>  “ifnot” <div data-bind="ifnot: displayMessage">Message is being displayed.</div> <script> ko.applyBindings({ displayMessage: ko.observable(false) }); </script> Note: similar to <div data-bind="if: !someProperty()">...</div>
  • 20.
     “with” Creates anew binding context, so that descendant elements are bound in the context of a specified object. <h1 data-bind="text: city"> </h1> <p data-bind="with: coords"> Latitude: <span data-bind="text: latitude"> </span>, Longitude: <span data-bind="text: longitude"> </span> </p> <script type="text/javascript"> ko.applyBindings({ city: "London", coords: { latitude: 51.5001524, longitude: -0.1262362 } }); </script>
  • 21.
    Form fields binding Click binding  Event Binding  Submit Binding  Enable Binding  Disable Binding  Value Binding  HasFocus Binding  Checked Binding  Options Binding  SelectedOptions Binding  The uniqueName binding
  • 22.
    Template Binding  Nativetemplating: Uses HTML markup contained in the body only. Built into knockout and doesn’t require any external library.  String-based templating: Knockout passes the model values to the external template engine and inject the resulting markup back into our document. Similar to what we were doing it till now using jQuery template. Other library being Underscore template engines.
  • 23.
    <h2>Participants</h2> Here are theparticipants: <div data-bind="template: { name: 'person-template', data: buyer }"></div> <div data-bind="template: { name: 'person-template', data: seller }"></div> <script type="text/html" id="person-template"> <h3 data-bind="text: name"></h3> <p>Credits: <span data-bind="text: credits"></span></p> </script> <script type="text/javascript"> function MyViewModel() { this.buyer = { name: 'Franklin', credits: 250 }; this.seller = { name: 'Mario', credits: 5800 }; } ko.applyBindings(new MyViewModel()); </script> NativeTemplating
  • 24.
    <h1>People</h1> <div data-bind="template: 'peopleList'"></div> <scripttype="text/html" id="peopleList"> {{each people}} <p> <b>${name}</b> is ${age} years old </p> {{/each}} </script> <script type="text/javascript"> var viewModel = { people: ko.observableArray([ { name: 'Rod', age: 123 }, { name: 'Jane', age: 125 }, ]) } ko.applyBindings(viewModel); </script> String-based Templating
  • 25.
    Click binding  Theclick binding is one of the simplest binding and is used to invoke a Javascript function associated with a DOM element based on a click. This binding works like event handler.  This is most commonly used with elements like button, input, and a, but actually works with any visible DOM element. Syntax  click: <binding-function>
  • 26.
    Click Binding Parameters  Mainparameter  The function you want to bind to the element’s click event.  You can reference any JavaScript function - it doesn’t have to be a function on your view model. You can reference a function on any object by writing click: someObject.someFunction.  Additional parameters  None
  • 27.
    $parent/$root:  If you’reinside a nested binding context,  for example if you’re inside a foreach or a with block, but your handler function is on the root viewmodel or some other parent context, you’ll need to use a prefix such as $parent or $root to locate the handler function.
  • 28.
    Click Binding <div data-bind="click:myDivHandler"> <button data-bind="click: myButtonHandler”> Click me </button> </div>
  • 29.
    Event Binding  Thisbinding is used to listen to specific DOM event and call associated handler function based on it. Syntax  event: <{DOM-event: handler-function}> Parameters  Parameter is inclusive of a Javascript object which contains DOM event which will be listened to and a handler function which needs to be invoked based on that event.
  • 30.
    Has Foucs Binding This binding is used to manually set the focus of a HTML DOM element through a ViewModel property. This is also a two ways binding method. When the element is focused from UI, Boolean value of ViewModel property is also changed and vice versa.
  • 31.
    Submit Binding  Thisbinding is used to invoke a Javascript function when the associated DOM element is submitted. This binding is used mostly for formelements.  The form is not actually submitted to server when submit binding is used. KO prevents browsers default action. If you want submit binding to work as real submit element then just return true from your handler function.
  • 32.
    Selected Options Binding This binding is used to work with elements which are selected currently in multi list select form control. This binding can be used with option binding and <select> form control only.  When the user selects or de-selects an item in the multi- select list, this adds or removes the corresponding value to an array on your view model. Assueme if it is an Observable array then items selected or de-selected from UI are also updated in array in ViewModel thus making it a two-way binding method.
  • 33.
    Knockout Validation  Includeknockout.validation.JS file into the project.  Use Extenders to implement the default validation. //start using it! var myValue = ko.observable().extend({ required: true }); //oooh complexity var myComplexValue = ko.observable().extend({ required: true, minLength: 3, pattern: { message: 'Hey this doesnt match my pattern', params: '^[A-Z0-9].$' } });
  • 34.
    Knockout Validation  InbuiltValidation  Required  Min  Max  MinLength  Digit  Email  Number  Pattern  Equal and not Equal  Custom
  • 35.
    Knockout JS UtilityFunctions  ko.utils.parseJson  ko.utils.arrayMap function Item(name, category, price) { this.name = ko.observable(name); this.category = ko.observable(category); this.price = ko.observable(price); this.priceWithTax = ko.dependentObservable(function() { return (this.price() * 1.05).toFixed(2); }, this); } //do some basic mapping (without mapping plugin) var mappedData = ko.utils.arrayMap(dataFromServer, function(item) { return new Item(item.name, item.category, item.price); });
  • 36.
    Knockout JS UtilityFunctions  ko.utils.arrayForEach  Array functions (filtering,sorting,Searching)  Ko.toJS()  Ko.toJSON()
  • 37.
    Custom bindings  Creatingcustom bindings You’re not limited to using the built-in bindings like click, value, and so on — you can create your own ones. This is how to control how observables interact with DOM elements, and gives you a lot of flexibility to encapsulate sophisticated behaviors in an easy-to- reuse way.
  • 38.
    Custom Bindings <div data-bind="yourBindingName:someValue"> </div> Note: you don’t actually have to provide both init and update callbacks — you can just provide one or the other if that’s all you need.
  • 39.
  • 40.
    Custom Binding Now youcan use this binding as follows: