Book Image

Mastering KnockoutJS

By : Timothy Moran
Book Image

Mastering KnockoutJS

By: Timothy Moran

Overview of this book

Table of Contents (16 chapters)
Mastering KnockoutJS
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Knockout-ES5


Knockout-ES5 is a plugin for Knockout that uses JavaScript getters and setters to hide observables behind object properties, allowing your application code to use standard syntax to work with them. Basically, it gets rid of the observable parentheses:

Take a look at the following code:

var latestOrder = this.orders()[this.orders().length - 1];
latestOrder.isShipped(true);

The preceding code becomes this:

var latestOrder = this.orders[this.orders.length - 1];
latestOrder.isShipped = true;

If you remember the Durandal observable plugin, it's very similar; they even came out around the same time. The biggest difference between the two is that Durandal's observable plugin performs deep object conversion, and Knockout ES5 performs shallow conversion.

To convert a viewmodel's properties to observables, call ko.track:

function Person(init) {
   var self = this,
      data = init || {};

   self.name = data.name || '';
   self.age = data.age || '';
self.alive = data.alive !== undefined ? data...