Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Knockout.JS Essentials
Knockout.JS Essentials

Knockout.JS Essentials: Implement a successful JavaScript-rich application with KnockoutJS, jQuery, and Bootstrap

eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Knockout.JS Essentials

Chapter 1. Refreshing the UI Automatically with KnockoutJS

If you are reading this book, it is because you have discovered that managing web user interfaces is quite complex. DOM (short for Document Object Model) manipulation using only native JavaScript is very hard. This is because each browser has its own JavaScript implementation. To solve this problem, different DOM manipulation libraries have been born in the last few years. The library most frequently used to manipulate the DOM is jQuery.

It is increasingly common to find libraries that help developers to manage more and more features on the client side. As we have said, developers have obtained the possibility to manipulate the DOM easily and therefore to manage templates and format data. Also, these libraries provide developers with easy APIs to send and receive data from the server.

However, DOM manipulation libraries don't provide us with mechanisms to synchronize input data with the models in our code. We need to write code that catches user actions and updates our models.

When a problem occurs frequently in most projects, in almost all the cases, it can surely be solved in a similar way. It was then that libraries that manage the connection between the HTML files and JavaScript code began to appear. The pattern these libraries implement was named MV* (Model-View-Whatever). The asterisk can be changed by:

  • Controller, MVC (for example, AngularJS)
  • ViewModel, MVVM (for example, KnockoutJS)
  • Presenter (MVP) (for example, ASP.NET)

The library we are going to use in this book is Knockout. It uses view-models to bind data and HTML, so it uses the MVVM pattern to manage the data binding issue.

In this chapter, you will learn the basic concepts of this library and you will begin a task to use Knockout in a real project.

KnockoutJS and the MVVM pattern

KnockoutJS is a very lightweight library (just 20 KB minified) that gives the ability to objects to become the nexus between views and models. It means that you can create rich interfaces with a clean underlying data model.

For this purpose, it uses declarative bindings to easily associate DOM elements with model data. This link between data and presentation layer (HTML) allows the DOM to refresh displayed values automatically.

Knockout set up chains of relationships between model data to transform and combine it implicitly. Knockout is also trivially extensible. It is possible to implement custom behaviors as new declarative bindings. This allows the programmer to reuse them in a just few lines of code.

The advantages of using KnockoutJS are many:

  • It's free and open source.
  • It is built using pure JavaScript.
  • It can work together with other frameworks.
  • It has no dependencies.
  • It supports all mainstream browsers, even ancient ones such as IE 6+, Firefox 3.5+, Chrome, Opera, and Safari (desktop/mobile).
  • It is fully documented with API docs, live examples, and interactive tutorials.

Knockout's function is specific: to join views and models. It doesn't manage DOM or handle AJAX requests. For these purposes, I would recommend jQuery. Knockout gives us the freedom to develop our code the way we want.

KnockoutJS and the MVVM pattern

MVVM-pattern diagram

A real-world application – koCart

In order to demonstrate how to use Knockout in a real application, we are going to build a simple shopping cart called koCart.

First of all we are going to define the user stories. We just need a few sentences to know what we want to achieve, which are as follows:

  • The user should be able to view the catalog
  • We should have the ability to search the catalog
  • The user can click on a button to add items to the catalog
  • The application will allow us to add, update, and delete items from the catalog
  • The user should be able to add, update, and delete items from the cart
  • We will allow the user to update his personal information.
  • The application should be able to calculate the total amount in the cart
  • The user should be able to complete an order

Through user stories, we can see that our application has the following three parts:

  • The catalog, which contains and manages all the products we have in the shop.
  • The cart, which has responsibility for calculating the price of each line and the total amount of the order.
  • The order, where the user can update his personal information and confirm the order.

Installing components

To develop our real-world project, we need to install a few components and set up our first layout.

These are all the components you need to download:

Since we just work on the client side in the first chapters, we can mock data in the client and will not need a server side for now. So we can choose any place in our computer to start our project. I recommend you use the environment you usually employ to do your projects.

To start, we create a folder called ko-cart and then create three folders and a file inside it:

  1. In the css folder, we will put all our css.
  2. In the js folder, we will put all our JavaScript.
  3. In the fonts folder, we will put all the font files needed by the Twitter Bootstrap framework.
  4. Create an index.html file.

Now you should set up your files the same way as shown in the following screenshot:

Installing components

The initial folder structure

Then we should set the content of the index.html file. Remember to set all the links to the files we will need using the <script> and <link> tags:

<!DOCTYPE html>
<html>
<head>
  <title>KO Shopping Cart</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>
<body>
  <script type="text/javascript" src="js/vendors/jquery.min.js">
  </script>
  <script type="text/javascript" src="js/vendors/bootstrap.min.js">
  </script>
  <script type="text/javascript" src="js/vendors/knockout.debug.js">
  </script>
</body>
</html>

With these lines of code, we have all we need to start our application.

The view-model

The view-model is a pure code representation of the data and operations on a UI. It isn't the UI itself. It doesn't have any concept of buttons or display styles. It's not the persisted data model either. It holds the unsaved data the user is working with. View-models are pure JavaScript objects that have no knowledge of HTML. Keeping the view-model abstract in this way lets it stay simple, so you can manage more sophisticated behaviors without getting lost.

To create a view-model, we just need to define a simple JavaScript object:

var vm = {};

Then to activate Knockout, we will call the following line:

ko.applyBindings(vm);

The first parameter says which view-model object we want to use with the view. Optionally, we can pass a second parameter to define which part of the document we want to search for data-bind attributes.

ko.applyBindings(vm, document.getElementById('elementID'));

This restricts the activation to the element with elementID and its descendants, which is useful if we want to have multiple view-models and associate each with a different region of the page.

The view

A view is a visible, interactive UI representing the state of the view-model. It displays information from the view-model, sends commands to the view-model (for example, when the user clicks on buttons), and updates whenever the state of the view-model changes. In our projects, views are represented by the HTML markups.

To define our first view, we are going to build an HTML to display a product. Add this new content to the container:

<div class="container-fluid">
  <div class="row">
    <div class="col-md-12">
      <!-- our app goes here →
      <h1>Product</h1>
      <div>
        <strong>ID:</strong>
        <span data-bind="text:product.id"></span><br/>
        <strong>Name:</strong>
        <span data-bind="text:product.name"></span><br/>
        <strong>Price:</strong>
        <span data-bind="text:product.price"></span><br/>
        <strong>Stock:</strong>
        <span data-bind="text:product.stock"></span>
      </div> 
    </div>
  </div>
</div>

Look at the data-bind attribute. This is called declarative binding. This attribute isn't native to HTML, though it is perfectly correct. But since the browser doesn't know what it means, you need to activate Knockout (the ko.applyBindings method) to make it take effect.

To display data from a product, we need to have a product defined inside our view-model:

var vm = {
  product: {
    id:1,
    name:'T-Shirt',
    price:10,
    stock: 20
  }
};
ko.applyBindings(vm);//This how knockout is activated

Add the view-model to the end of the script tags:

<script type="text/javascript" src="js/viewmodel.js"></script>

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

This will be the result of our app:

The view

Result of data binding

The model

This data represents objects and operations in your business domain (for example, products) and is independent of any UI. When using Knockout, you will usually make AJAX calls to some server-side code to read and write this stored model data.

Models and view-models should be separated from each other. In order to define our product model, we are going to follow some steps:

  1. Create a folder inside our js folder.
  2. Name it models.
  3. Inside the models folder, create a JavaScript file called product.js.

The code of the product.js file is as follows:

var Product = function (id,name,price,stock) {
  "use strict";
  var
    _id = id,
    _name = name,
    _price = price,
    _stock = stock
  ;

  return {
    id:_id,
    name:_name,
    price:_price,
    stock:_stock
  };
};

This function creates a simple JavaScript object that contains the interface of the product. Defining the object using this pattern, called the revealing module pattern, allows us to clearly separate public elements from private elements.

To learn more about the revealing module pattern, follow the link https://carldanley.com/js-revealing-module-pattern/.

Link this file with your index.html file and set it at the bottom of all the script tags.

<script type="text/javascript" src="js/models/product.js">
</script>

Now we can use the product model to define the product in the view-model:

var vm = {
  product: Product(1,'T-Shirt',10,20);
};
ko.applyBindings(vm);

If we run the code again, we will see the same result, but our code is more readable now. View-models are used to store and handle a lot of information, because of this view-models are commonly treated as modules and the revealing module pattern is applied on them. This pattern allows us in a clear manner to expose the API (public elements) of the view-model and hide private elements.

var vm = (function(){
  var product = Product(1,'T-Shirt', 10, 20);
  return {
    product: product
  };
})();

Using this pattern when our view-model begins to grow helps us to clearly see which elements belong to the public part of the object and which ones are private.

Observables to refresh the UI automatically

The last example shows us how Knockout binds data and the user interface, but it doesn't show the magic of the automatic UI refresh. To perform this task, Knockout uses observables.

Observables are the main concept of Knockout. These are special JavaScript objects that can notify subscribers about changes, and can automatically detect dependencies. For compatibility, ko.observable objects are actually functions.

To read an observable's current value, just call the observable with no parameters. In this example, product.price() will return the price of the product, and product.name() will return the name of the product.

var product = Product(1,"T-Shirt", 10.00, 20);
product.price();//returns 10.00
product.name();//returns "T-Shirt"

To write a new value to the observable, call the observable and pass the new value as a parameter. For example, calling product.name('Jeans') will change the name value to 'Jeans'.

var product = Product(1,"T-Shirt", 10.00, 20);
product.name();//returns "T-Shirt"
product.name("Jeans");//sets name to "Jeans"
product.name();//returns "Jeans"

The complete documentation about observables is on the official Knockout website http://knockoutjs.com/documentation/observables.html.

To show how observables work, we are going to add some input data into our template.

Add these HTML tags over div that contain product information.

<div>
  <strong>ID:</strong>
  <input class="form-control" type="text" data-bind="value:product.id"/><br/>
  <strong>Name:</strong>
  <input class="form-control" type="text" data-bind="value:product.name"><br/>
  <strong>Price:</strong>
  <input class="form-control" type="text" data-bind="value:product.price"/><br/>
  <strong>Stock:</strong>
  <input class="form-control" type="text" data-bind="value:product.stock"><br/>
</div>

We have linked inputs to the view-model using the value property. Run the code and try to change the values in the inputs. What happened? Nothing. This is because variables are not observables. Update your product.js file, adding the ko.observable method to each variable:

"use strict";
function Product(id, name, price, stock) {
  "use strict";
  var
    _id = ko.observable(id),
    _name = ko.observable(name),
    _price = ko.observable(price),
    _stock = ko.observable(stock)
  ;

  return {
    id:_id,
    name:_name,
    price:_price,
    stock:_stock
  };
}

Notice that when we update the data inside the inputs, our product values are updated automatically. When you change the name value to Jeans, the text binding will automatically update the text content of the associated DOM element. That's how changes to the view-model automatically propagate to the view.

Observables to refresh the UI automatically

Observable models are updated automatically

Managing collections with observables

If you want to detect and respond to changes in one object, you'd use observables. If you want to detect and respond to changes in a collection of things, use an observableArray. This is useful in many scenarios where you're displaying or editing multiple values and need repeated sections of the UI to appear and disappear as items are added and removed.

To display a collection of products in our application, we are going to follow some simple steps:

  1. Open the index.html file and remove the code inside the <body> tag and then add a table where we will list our catalog:
    <h1>Catalog</h1>
    <table class="table">
      <thead>
        <tr>
          <th>Name</th>
          <th>Price</th>
          <th>Stock</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td></td>
          <td></td>
          <td></td>
        </tr>
      </tbody>
    </table>
  2. Define an array of products inside the view-model:
    "use strict";
    var vm = (function () {
    
      var catalog = [
        Product(1, "T-Shirt", 10.00, 20),
        Product(2, "Trousers", 20.00, 10),
        Product(3, "Shirt", 15.00, 20),
        Product(4, "Shorts", 5.00, 10)
      ];
    
      return {
        catalog: catalog
      };
    })();
    ko.applyBindings(vm);
  3. Knockout has a binding to repeat a piece of code for each element in a collection. Update the tbody element in the table:
    <tbody data-bind="foreach:catalog">
      <tr>
        <td data-bind="text:name"></td>
        <td data-bind="text:price"></td>
        <td data-bind="text:stock"></td>
      </tr>
    </tbody>

We use the foreach property to point out that all that is inside this tag should be repeated for each item in the collection. Inside this tag we are in the context of each element, so you can just bind properties directly. Observe the result in your browser.

We want to know how many items we have in our catalog, so add this line of code above the table:

<strong>Items:</strong>
<span data-bind="text:catalog.length"></span>

Inserting elements in collections

To insert elements in the products array, an event should occur. In this case, the user will click on a button and this action will fire an action that will insert a new product in the collection.

In future chapters, you will learn more about events. Now we will just need to know that there is a binding property named click. It receives a function as a parameter, and this function is fired when the user clicks on the element.

To insert an element, we need a form to insert the values of the new product. Write this HMTL code just below the <h1> tag:

<form class="form-horizontal" role="form" data-bind="with:newProduct">
  <div class="form-group">
    <div class="col-sm-12">
      <input type="text" class="form-control" placeholder="Name" data-bind="textInput:name">
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-12">
      <input type="password" class="form-control" placeholder="Price" data-bind="textInput:price">
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-12">
      <input type="password" class="form-control" placeholder="Stock" data-bind="textInput:stock">
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-12">
      <button type="submit" class="btn btn-default" data-bind="{click:$parent.addProduct}">
        <i class="glyphicon glyphicon-plus-sign">
        </i> Add Product
      </button>
    </div>
  </div>
</form>

In this template, we find some new bindings:

  • The with binding: This creates a new binding context so that descendant elements are bound in the context of a specified object, in this case newProduct.

    http://knockoutjs.com/documentation/with-binding.html

  • The textInput binding: The textInput binding links a textbox (<input>) or text area (<textarea>) with a view-model property, providing two-way updates between the viewmodel property and the element's value. Unlike the value binding property, textInput provides instant updates from the DOM for all types of user input, including autocomplete, drag-and-drop, and clipboard events. It is available from the 3.2 version of Knockout.

    http://knockoutjs.com/documentation/textinput-binding.html

  • The click binding: The click binding adds an event handler so that your chosen JavaScript function is invoked when the associated DOM element is clicked. When calling your handler, Knockout will supply the current model value as the first parameter. This is particularly useful if you're rendering UI for each item in a collection, and you need to know which item's UI was clicked.

    http://knockoutjs.com/documentation/click-binding.html

  • The $parent object: This is a binding context property. We use it to refer to data from outside the foreach loop.

For more information about binding context properties, read the Knockout documentation at http://knockoutjs.com/documentation/binding-context.html.

Inserting elements in collections

Using with to set a context and parent to navigate through them

Now it is time to add the newProduct object to our view-model. First we should define a new product with empty data:

var newProduct = Product("","","","");

We have defined a literal object that will contain the information we want to put inside our new product. Also, we have defined a method to clear or reset the object once the insertion is done. Now we define our addProduct method:

var addProduct = function (context) {
  var id = new Date().valueOf();//random id from time
  var newProduct = Product(
    id,
    context.name(),
    context.price(),
    context.stock()
  );
  catalog.push(newProduct);
  newProduct.clear();
};

This method creates a new product with the data received from the click event.

The click event always sends the context as the first argument. Note also that you can use array methods such as push in an observable array. Check out the Knockout documentation (http://knockoutjs.com/documentation/observableArrays.html) to see all the methods available in arrays.

We should implement the private method that will clean data from the new product once it is added to the collection:

var clearNewProduct = function () {
  newProduct.name("");
  newProduct.price("");
  newProduct.stock("");
};

Update the view-model:

return {
    catalog: catalog,
    newProduct: newProduct,
    addProduct: addProduct
};

If you run the code, you will notice that when you try to add a new product nothing happens. This is because, despite the fact that our products have observable properties, our array is not an observable one. For this reason, Knockout is not listening to the changes. We should convert the array to an observableArray observable.

var catalog = ko.observableArray([
  Product(1, "T-Shirt", 10.00, 20),
  Product(2, "Trousers", 20.00, 10),
  Product(3, "Shirt", 15.00, 20),
  Product(4, "Shorts", 5.00, 10)
]);

Now Knockout is listening to what is going on with this array, but not what is happening inside each element. Knockout just tells us about inserting or deleting elements in the array, but not about editing elements. If you want to know what is happening in an element, the object should have observable properties.

An observableArray observable just tracks which objects it holds, and notifies listeners when objects are added or removed.

Behind the scenes, the observableArray is actually an observable whose value is an array. So you can get the underlying JavaScript array by invoking the observableArray observable as a function with no parameters, just like any other observable. Then you can read information from that underlying array.

<strong>Items:</strong>
<span data-bind="text:catalog().length"></span>

Computed observables

It is not weird to think that some values we show in our interface depend on other values that Knockout is already observing. For example, if we would like to search products in our catalog by name, it is evident that the products in the catalog that we show in the list are related to the term we have entered in the search box. In these cases Knockout offers us computed observables.

You can learn in detail about computed observables in the Knockout documentation at http://knockoutjs.com/documentation/computedObservables.html.

To develop the search function, define a textbox where we can write a term to search. We are going to bind it to the searchTerm property. To update the value as we write, we should use the textInput binding. If we use the value binding, the value will be updated when the element loses the focus. Put this code over the products table:

<div class="input-group">
  <span class="input-group-addon">
    <i class="glyphicon glyphicon-search"></i> Search</span>
  <input type="text" class="form-control" data-bind="textInput: searchTerm">
</div>

To create a filtered catalog, we are going to check all our items and test if the searchTerm is in the item's name property.

var searchTerm = ko.observable(''); 
var filteredCatalog = ko.computed(function () {
  //if catalog is empty return empty array
  if (!catalog()) {
    return [];
  }
  var filter = searchTerm().toLowerCase();
  //if filter is empty return all the catalog
  if (!filter) {
    return catalog();
  }
  //filter data
  var filtered = ko.utils.arrayFilter(catalog(), function (item) {
    var fields = ["name"]; //we can filter several properties
    var i = fields.length;
    while (i--) {
      var prop = fields[i];
      var strProp = ko.unwrap(item[prop]).toLocaleLowerCase();
      if (strProp.indexOf(filter) !== -1){
        return true;
      };
    }
    Return false;
  });
  return filtered;
});

The ko.utils object is not documented in Knockout. It is an object used by the library internally. It has public access and has some functions that can help us with observables. There are a lot of unofficial examples about it on the Internet.

One of its helpful functions is ko.utils.arrayFilter. If you look at line 13, we have used this method to obtain a filtered array.

This function gets an array as the first parameter. Notice that we invoke the catalog array observable to get the elements. We don't pass the observable itself, but the contents of the observable.

The second parameter is the function that decides whether the item will be in the filtered array or not. It will return true if the item has the conditions to be in the filtered array. Otherwise it returns false.

On line 14 of this snippet, we can find an array called fields. This parameter will contain the fields that should comply with the criteria. In this case, we just check that the filter value is in the name value. If we are pretty sure that we are just going to check the name field, we can simplify the filter function:

var filtered = ko.utils.arrayFilter(catalog(), function (item) {
  var strProp = ko.unwrap(item["name"]).toLocaleLowerCase();
  return (strProp.indexOf(filter) > -1);
});

The ko.unwrap function returns the value that contains the observable. We use ko.unwrap when we are not sure if the variable contains an observable or not, for example:

var notObservable = 'hello';
console.log(notObservable()) //this will throw an error.
console.log(ko.unwrap(notObservable)) //this will display 'hello');

Expose the filtered catalog into the public API. Notice that now we need to use the filtered catalog instead of the original catalog of products. Because we are applying the revealing module pattern, we can keep the original API interface and just update the value of the catalog with the filtered catalog. We don't need to alert the view that we are going to use a different catalog or other element, as long as we always maintain the same public interface:

return {
  searchTerm: searchTerm,
  catalog: filteredCatalog,
  newProduct: newProduct,
  addProduct: addProduct
};

Now, try to type some characters in the search box and see in your browser how the catalog updates the data automatically.

Wonderful! We have completed our first three user stories:

  • The user should be able to view the catalog
  • The user should be able to search the catalog
  • The user should be able to add items to the catalog

Let's see the final result:

Computed observables

Summary

In this chapter, you have learned the basics of the Knockout library. We have created a simple form to add products to our catalog. You have also learned how to manage observable collections and display them in a table. Finally, we have developed the search functionality using computed observables.

You have learned three important Knockout concepts:

  • View-model: This holds the data that represents the state of the view. It is a pure JavaScript object.
  • Models: This contains data from the business domain.
  • Views: This displays the data we store in the view-model in a given instant of time.

To build reactive UIs, the Knockout library provides us with some important methods:

  • ko.observable: This is used to manage variables.
  • ko.observableArray: This is used to manage arrays.
  • ko.computed: They respond to changes from observables that are inside them.

To iterate over the elements of an array, we use the foreach binding. When we use the foreach binding, we create a new context. This context is relative to each item. If we want to access out of this context we should use the $parent object.

When we want to create a new context relative to a variable, we can attach the with binding to any DOM element.

We use the click binding to attach the click event to an element. Click on event functions to always get the context as the first parameter.

To get values from a variable that we are not sure is an observable, we can use the ko.unwrap function.

We can use the ko.utils.arrayFilter function to filter collections.

In the next chapter, we are going to use templates to keep our code maintainable and clean. Template engines help us to keep our code arranged and allow us to update views in an easy way.

There is a copy of the code developed in this chapter at:

https://github.com/jorgeferrando/knockout-cart/archive/chapter1.zip.

Left arrow icon Right arrow icon

Description

If you are a JavaScript developer who has been using DOM manipulation libraries such as Mootools or Scriptaculous, and you want go further in modern JavaScript development with a simple and well-documented library, then this book is for you. Learning how to use Knockout will be perfect as your next step towards building JavaScript applications that respond to user interaction.

Who is this book for?

If you are a JavaScript developer who has been using DOM manipulation libraries such as Mootools or Scriptaculous, and you want go further in modern JavaScript development with a simple and well-documented library, then this book is for you. Learning how to use Knockout will be perfect as your next step towards building JavaScript applications that respond to user interaction.

What you will learn

  • Organize and maintain your code when applications begin to grow
  • Get to know JavaScript patterns and best practices to keep your code readable
  • Bind JavaScript objects and DOM elements with practical examples
  • Integrate and manage events to give the user a better experience
  • Extend the framework to create your own components
  • Create a singlepage application using the Durandal JavaScript framework
  • Split your application in modules to keep it engrossing and maintainable
  • Manage templates to keep your HTML as simple as possible

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 27, 2015
Length: 232 pages
Edition : 1st
Language : English
ISBN-13 : 9781784395285
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Feb 27, 2015
Length: 232 pages
Edition : 1st
Language : English
ISBN-13 : 9781784395285
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 99.97
KnockoutJS Web Development
€24.99
Knockout.JS Essentials
€32.99
MASTERING KNOCKOUTJS
€41.99
Total 99.97 Stars icon
Banner background image

Table of Contents

9 Chapters
1. Refreshing the UI Automatically with KnockoutJS Chevron down icon Chevron up icon
2. KnockoutJS Templates Chevron down icon Chevron up icon
3. Custom Bindings and Components Chevron down icon Chevron up icon
4. Managing KnockoutJS Events Chevron down icon Chevron up icon
5. Getting Data from the Server Chevron down icon Chevron up icon
6. The Module Pattern – RequireJS Chevron down icon Chevron up icon
7. Durandal – The KnockoutJS Framework Chevron down icon Chevron up icon
8. Developing Web Applications with Durandal – The Cart Project Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(2 Ratings)
5 star 50%
4 star 0%
3 star 50%
2 star 0%
1 star 0%
Alexander Fyodorov Apr 16, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Brilliant book. Methodically correct - its main working example is being enhanced part by part during the course of the chapters. I really like the patterns of KO usage summarized here (actually theyare the best patterns to work with javascript anyway). Don't manipulate DOM within the ViewModel, use declarative bindings in the HTML vews. Don't call Ajax from the VMs - use services that can be easily mocked. Use pure models (without presentational details) within VMs. Modularize code with RequireJS, use Durandal framework to facilitate many routine tasks.Highly recommend this book to anyone writing large Single Page Applications.
Amazon Verified review Amazon
Stephen L. Mcconnell Aug 01, 2016
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
It is a pretty good book. However, there are typos (which one can figure out) and I cannot get a copy of the source files. The examples in the book are confusing (if one has never worked with Knockout JS) and the book often just plops a new function or HTML section without explaining where they go. I beat my head against the wall for half a day before I realized that where the javascript goes is important and the "data-bind" won't work if you put your javascript in the wrong place. I'm new to Javascript and Knockout and am totally frustrated.UPDATE:As I get more into the book and understand more, it becomes less confusing. I have updated this review to three stars. Once I figured out some of the seemingly obfuscated nuances about the writing style and example style, the examples are working better.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.