Book Image

KnockoutJS Essentials

By : Jorge Ferrando, Jorge F Ferrando
Book Image

KnockoutJS Essentials

By: Jorge Ferrando, Jorge F Ferrando

Overview of this book

Table of Contents (16 chapters)
KnockoutJS Essentials
About the Author
About the Reviewers

Create a binding to debug – the toJSON binding

When we develop our project, we make mistakes and we find unexpected behaviors. The Knockout view-model is hard to read because we don't have plain objects, we have observables. Because of this, maybe it's useful to have a method and a container inside our application that shows us the state of the view-model during the development process. This is why we are going to build a toJSON binding that becomes our view-model into a plain JSON object that we can show into the screen or in our console.

ko.bindingHandlers.toJSON = {
  update: function(element, valueAccessor){
    return ko.bindingHandlers.text.update(element,function(){
      return ko.toJSON(valueAccessor(), null, 2);

We have used the ko.toJSON object to convert the value we get into a JSON object.

This function has the same interface that the native JSON.stringify function has. It gets three parameters as arguments:

The first parameter is the object we want to convert into...