SlideShare a Scribd company logo
Simplify dynamic JavaScript UIs by applying the
             Model-View-ViewModel(MVVM)
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.
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
Is it different from jQuery or any
other javascript framework?
jQuery/js Frameworks                 Knockout
 Basically a replacement for the     Knockout provides a
  clunky, inconsistent DOM APIs        complementary, high-level way
  we had to put up with in the         to link a data model to a UI.
  past.
 A low-level way to manipulate
  elements and event handlers in a
  web page.


  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.
NativeTemplating
<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>
String-based Templating
<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>

More Related Content

KEY
Knockout.js presentation
PPTX
Fundaments of Knockout js
PDF
Knockout js session
PPT
KnockoutJS and MVVM
PDF
An introduction to knockout.js
PPTX
PPTX
Web components
PDF
Backbone js
Knockout.js presentation
Fundaments of Knockout js
Knockout js session
KnockoutJS and MVVM
An introduction to knockout.js
Web components
Backbone js

What's hot (20)

PDF
Knockoutjs databinding
PDF
The Complementarity of React and Web Components
KEY
AngularJS for designers and developers
PDF
JavaScript and BOM events
PDF
React 소개 및 구현방법 Demo
PDF
React
PDF
Why and How to Use Virtual DOM
PDF
Modern frontend development with VueJs
PPTX
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
PPTX
Dom selecting & jQuery
PDF
Modern Web Application Development Workflow - EclipseCon Europe 2014
PDF
22 j query1
PDF
Backbone.js
PDF
handout-05b
PDF
Web Components + Backbone: a Game-Changing Combination
PDF
Building a Startup Stack with AngularJS
PPTX
The AngularJS way
PDF
Javascript and DOM
PDF
Web Components
PDF
Difference between java script and jquery
Knockoutjs databinding
The Complementarity of React and Web Components
AngularJS for designers and developers
JavaScript and BOM events
React 소개 및 구현방법 Demo
React
Why and How to Use Virtual DOM
Modern frontend development with VueJs
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Dom selecting & jQuery
Modern Web Application Development Workflow - EclipseCon Europe 2014
22 j query1
Backbone.js
handout-05b
Web Components + Backbone: a Game-Changing Combination
Building a Startup Stack with AngularJS
The AngularJS way
Javascript and DOM
Web Components
Difference between java script and jquery
Ad

Viewers also liked (20)

PPTX
Introduction to Knockoutjs
PPTX
Knockout.js explained
PDF
Fundamentals of Extending Magento 2 - php[world] 2015
PPTX
#2 Hanoi Magento Meetup - Part 2: Knockout JS
PDF
Bootstrap3 Тарас Мудрий
PDF
RequireJS і Magento 2
PPTX
#speakgeek - Angular JS
PPTX
Angular JS and Magento
PPT
#2 Hanoi Magento meetup - Part 1: Be part of the world
PPTX
#3 Hanoi Magento Meetup - Part 1: Magento Around The World
PPTX
#2 Hanoi Magento Meetup - Part 3: Panel discussion
PPTX
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
PPTX
Knockout js
PPTX
knockout.js
PDF
Knockout js (Dennis Haney)
PPTX
Knockout (support slides for presentation)
PPTX
#3 Hanoi Magento Meetup - Part 3: Magento Website Optimization
PPTX
Knockout js
PPT
Knockout.js
PPTX
Knockout JS Development - a Quick Understanding
Introduction to Knockoutjs
Knockout.js explained
Fundamentals of Extending Magento 2 - php[world] 2015
#2 Hanoi Magento Meetup - Part 2: Knockout JS
Bootstrap3 Тарас Мудрий
RequireJS і Magento 2
#speakgeek - Angular JS
Angular JS and Magento
#2 Hanoi Magento meetup - Part 1: Be part of the world
#3 Hanoi Magento Meetup - Part 1: Magento Around The World
#2 Hanoi Magento Meetup - Part 3: Panel discussion
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
Knockout js
knockout.js
Knockout js (Dennis Haney)
Knockout (support slides for presentation)
#3 Hanoi Magento Meetup - Part 3: Magento Website Optimization
Knockout js
Knockout.js
Knockout JS Development - a Quick Understanding
Ad

Similar to Knockout.js (20)

PPTX
Asp.NET MVC
PPTX
Asp.net mvc training
PPTX
Knockoutjs Part 4 Bindings Controlling text and appearance
PDF
MVVM & Data Binding Library
PDF
Creating lightweight JS Apps w/ Web Components and lit-html
PPT
Backbone.js
PDF
Spca2014 hillier 3rd party_javascript_libraries
PPTX
AngularJs Workshop SDP December 28th 2014
PDF
Angular - Chapter 4 - Data and Event Handling
PPTX
MVC and Razor - Doc. v1.2
PDF
Web Components Everywhere
PDF
Web Components for Java Developers
PPTX
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling
PDF
Deep dive into Android Data Binding
PDF
AngularJS 101 - Everything you need to know to get started
PDF
Single page webapps & javascript-testing
PDF
Knockoutjs
PDF
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
DOCX
Adding a view
PPTX
Angular js
Asp.NET MVC
Asp.net mvc training
Knockoutjs Part 4 Bindings Controlling text and appearance
MVVM & Data Binding Library
Creating lightweight JS Apps w/ Web Components and lit-html
Backbone.js
Spca2014 hillier 3rd party_javascript_libraries
AngularJs Workshop SDP December 28th 2014
Angular - Chapter 4 - Data and Event Handling
MVC and Razor - Doc. v1.2
Web Components Everywhere
Web Components for Java Developers
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling
Deep dive into Android Data Binding
AngularJS 101 - Everything you need to know to get started
Single page webapps & javascript-testing
Knockoutjs
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Adding a view
Angular js

Recently uploaded (20)

PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Machine learning based COVID-19 study performance prediction
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Encapsulation theory and applications.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
KodekX | Application Modernization Development
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
Understanding_Digital_Forensics_Presentation.pptx
Review of recent advances in non-invasive hemoglobin estimation
Machine learning based COVID-19 study performance prediction
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Empathic Computing: Creating Shared Understanding
NewMind AI Monthly Chronicles - July 2025
Encapsulation theory and applications.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
KodekX | Application Modernization Development
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Reach Out and Touch Someone: Haptics and Empathic Computing
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Spectral efficient network and resource selection model in 5G networks
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
MYSQL Presentation for SQL database connectivity
Digital-Transformation-Roadmap-for-Companies.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”

Knockout.js

  • 1. Simplify dynamic JavaScript UIs by applying the Model-View-ViewModel(MVVM)
  • 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.
  • 3. 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
  • 4. 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
  • 5. Is it different from jQuery or any other javascript framework? jQuery/js Frameworks Knockout  Basically a replacement for the  Knockout provides a clunky, inconsistent DOM APIs complementary, high-level way we had to put up with in the to link a data model to a UI. past.  A low-level way to manipulate elements and event handlers in a web page. Note: Both can be used in solution seamlessly.
  • 6. Core Features  Observables and dependency tracking  Declarative bindings  Templating
  • 7. 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>
  • 8. 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) };
  • 9. 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
  • 10. 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>
  • 11. 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>
  • 12.  “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>
  • 13.  “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>
  • 14.  “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.
  • 15. Control Flow Statements  “foreach”  “if”  “ifnot”  “with”
  • 16.  “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>
  • 17. </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>
  • 18.  “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>
  • 19.  “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>
  • 20. 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
  • 21. 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.
  • 22. NativeTemplating <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>
  • 23. String-based Templating <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>