SlideShare a Scribd company logo
1 of 23
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

What's hot

Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databindingBoulos Dib
 
The Complementarity of React and Web Components
The Complementarity of React and Web ComponentsThe Complementarity of React and Web Components
The Complementarity of React and Web ComponentsAndrew Rota
 
AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developersKai Koenig
 
React 소개 및 구현방법 Demo
React 소개 및 구현방법 DemoReact 소개 및 구현방법 Demo
React 소개 및 구현방법 DemoDaesung Kim
 
Why and How to Use Virtual DOM
Why and How to Use Virtual DOMWhy and How to Use Virtual DOM
Why and How to Use Virtual DOMDaiwei Lu
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJsTudor Barbu
 
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Ayes Chinmay
 
Dom selecting & jQuery
Dom selecting & jQueryDom selecting & jQuery
Dom selecting & jQueryKim Hunmin
 
Modern Web Application Development Workflow - EclipseCon Europe 2014
Modern Web Application Development Workflow - EclipseCon Europe 2014Modern Web Application Development Workflow - EclipseCon Europe 2014
Modern Web Application Development Workflow - EclipseCon Europe 2014Stéphane Bégaudeau
 
Web Components + Backbone: a Game-Changing Combination
Web Components + Backbone: a Game-Changing CombinationWeb Components + Backbone: a Game-Changing Combination
Web Components + Backbone: a Game-Changing CombinationAndrew Rota
 
Building a Startup Stack with AngularJS
Building a Startup Stack with AngularJSBuilding a Startup Stack with AngularJS
Building a Startup Stack with AngularJSFITC
 
Difference between java script and jquery
Difference between java script and jqueryDifference between java script and jquery
Difference between java script and jqueryUmar Ali
 

What's hot (20)

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

Viewers also liked

Introduction to Knockoutjs
Introduction to KnockoutjsIntroduction to Knockoutjs
Introduction to Knockoutjsjhoguet
 
Fundamentals of Extending Magento 2 - php[world] 2015
Fundamentals of Extending Magento 2 - php[world] 2015Fundamentals of Extending Magento 2 - php[world] 2015
Fundamentals of Extending Magento 2 - php[world] 2015David Alger
 
#2 Hanoi Magento Meetup - Part 2: Knockout JS
#2 Hanoi Magento Meetup - Part 2: Knockout JS#2 Hanoi Magento Meetup - Part 2: Knockout JS
#2 Hanoi Magento Meetup - Part 2: Knockout JSHanoi MagentoMeetup
 
Bootstrap3 Тарас Мудрий
Bootstrap3 Тарас МудрийBootstrap3 Тарас Мудрий
Bootstrap3 Тарас МудрийHRdepartment
 
#speakgeek - Angular JS
#speakgeek - Angular JS#speakgeek - Angular JS
#speakgeek - Angular JSDerek Chan
 
Angular JS and Magento
Angular JS and MagentoAngular JS and Magento
Angular JS and MagentoVinci Rufus
 
#2 Hanoi Magento meetup - Part 1: Be part of the world
#2 Hanoi Magento meetup - Part 1: Be part of the world#2 Hanoi Magento meetup - Part 1: Be part of the world
#2 Hanoi Magento meetup - Part 1: Be part of the worldHanoi MagentoMeetup
 
#3 Hanoi Magento Meetup - Part 1: Magento Around The World
#3 Hanoi Magento Meetup - Part 1: Magento Around The World#3 Hanoi Magento Meetup - Part 1: Magento Around The World
#3 Hanoi Magento Meetup - Part 1: Magento Around The WorldHanoi MagentoMeetup
 
#2 Hanoi Magento Meetup - Part 3: Panel discussion
#2 Hanoi Magento Meetup - Part 3: Panel discussion#2 Hanoi Magento Meetup - Part 3: Panel discussion
#2 Hanoi Magento Meetup - Part 3: Panel discussionHanoi MagentoMeetup
 
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With ContainersHanoi MagentoMeetup
 
Knockout (support slides for presentation)
Knockout (support slides for presentation)Knockout (support slides for presentation)
Knockout (support slides for presentation)Aymeric Gaurat-Apelli
 
#3 Hanoi Magento Meetup - Part 3: Magento Website Optimization
#3 Hanoi Magento Meetup - Part 3: Magento Website Optimization#3 Hanoi Magento Meetup - Part 3: Magento Website Optimization
#3 Hanoi Magento Meetup - Part 3: Magento Website OptimizationHanoi MagentoMeetup
 
Knockout js
Knockout jsKnockout js
Knockout jshhassann
 
Knockout JS Development - a Quick Understanding
Knockout JS Development - a Quick UnderstandingKnockout JS Development - a Quick Understanding
Knockout JS Development - a Quick UnderstandingUdaya Kumar
 

Viewers also liked (20)

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

Similar to Knockout.js

Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc trainingicubesystem
 
Knockoutjs Part 4 Bindings Controlling text and appearance
Knockoutjs Part 4  Bindings  Controlling text and appearanceKnockoutjs Part 4  Bindings  Controlling text and appearance
Knockoutjs Part 4 Bindings Controlling text and appearanceBhaumik Patel
 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library 10Clouds
 
Creating lightweight JS Apps w/ Web Components and lit-html
Creating lightweight JS Apps w/ Web Components and lit-htmlCreating lightweight JS Apps w/ Web Components and lit-html
Creating lightweight JS Apps w/ Web Components and lit-htmlIlia Idakiev
 
Spca2014 hillier 3rd party_javascript_libraries
Spca2014 hillier 3rd party_javascript_librariesSpca2014 hillier 3rd party_javascript_libraries
Spca2014 hillier 3rd party_javascript_librariesNCCOMMS
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014Ran Wahle
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
 
MVC and Razor - Doc. v1.2
MVC and Razor - Doc. v1.2MVC and Razor - Doc. v1.2
MVC and Razor - Doc. v1.2Naji El Kotob
 
Web Components Everywhere
Web Components EverywhereWeb Components Everywhere
Web Components EverywhereIlia Idakiev
 
Web Components for Java Developers
Web Components for Java DevelopersWeb Components for Java Developers
Web Components for Java DevelopersJoonas Lehtinen
 
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling Sencha
 
Deep dive into Android Data Binding
Deep dive into Android Data BindingDeep dive into Android Data Binding
Deep dive into Android Data BindingRadek Piekarz
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedStéphane Bégaudeau
 
Single page webapps & javascript-testing
Single page webapps & javascript-testingSingle page webapps & javascript-testing
Single page webapps & javascript-testingsmontanari
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
 
Adding a view
Adding a viewAdding a view
Adding a viewNhan Do
 

Similar to Knockout.js (20)

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

Recently uploaded

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

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>