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

Arrow left icon
Profile Icon Ferrando
Arrow right icon
S$59.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (2 Ratings)
Paperback Feb 2015 232 pages 1st Edition
eBook
S$12.99 S$47.99
Paperback
S$59.99
Subscription
Free Trial
Arrow left icon
Profile Icon Ferrando
Arrow right icon
S$59.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (2 Ratings)
Paperback Feb 2015 232 pages 1st Edition
eBook
S$12.99 S$47.99
Paperback
S$59.99
Subscription
Free Trial
eBook
S$12.99 S$47.99
Paperback
S$59.99
Subscription
Free Trial

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Singapore

Standard delivery 10 - 13 business days

S$11.95

Premium delivery 5 - 8 business days

S$54.95
(Includes tracking information)

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 : 9781784397074
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Singapore

Standard delivery 10 - 13 business days

S$11.95

Premium delivery 5 - 8 business days

S$54.95
(Includes tracking information)

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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 S$6 each
Feature tick icon Exclusive print discounts
$279.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 S$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total S$ 179.97
KnockoutJS Web Development
S$44.99
Knockout.JS Essentials
S$59.99
MASTERING KNOCKOUTJS
S$74.99
Total S$ 179.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

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela