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.
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:
We use the
ko.extenders
object to create a new extender by adding a new property. In the preceding example, the property name islogChange
. 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...