Book Image

Getting Started with Knockout.js for .NET Developers

By : Andrey Ankshin
Book Image

Getting Started with Knockout.js for .NET Developers

By: Andrey Ankshin

Overview of this book

Table of Contents (14 chapters)
Getting Started with Knockout.js for .NET Developers
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Extending observables


Observables are a very useful and powerful part of Knockout.js. They allow you to create flexible and reliable applications. However, sometimes, you need to extend the opportunities of your observable properties. The extenders help you! As usual, let's proceed with some examples from the official documentation in detail.

Creating an extender

In this section, we will write a simple extender, as follows:

ko.extenders.logChange = function(target, option) { // 1
  target.subscribe(function(newValue) { // 2
    console.log(option + ": " + newValue); // 3
  });
  return target; // 4
};

Let's discuss it in detail:

  1. We use the ko.extenders object to create a new extender by adding a new property. In the preceding example, the property name is logChange. This extender will log any changes of the target binding value. In fact, an extender is just a function with two parameters. The first parameter (target) is the observable itself, the second parameter (option) is any option to define...