Knockout.js Succinctly (1)

Knockout.js provides a cleaner way to manage data changes on the web page. (data driven interfaces). Instead of manually tracking which sections of the HTML page reply on the affected data, KO lets you create a direct connection between the underlying data and its presentation (HTML). After linking an HTML element with a particular data object, any change to that object are automatically reflected in the DOM.

[Delete Item] –-> [Date] –(automatically change) –> [HTML Page]
image

This allows you to focus on the data behind your application. After you set up your HTML templates, you can work exclusively with JS data objects. With KO, all you have to do to remove an item from the shopping cart is remove it from the javascript array that represents the user’s shopping cart item.

KO let you design a self-updating display for your JS objects. That are others features too.
It’s easy to extend KO.
KO comes with several utility functions, including array filters, JSON parsing, and a generic way to map data from the server to an HTML view.

What KO is not
Not to replace jQuery, Prototype or MooTools. it does not attempt to do animation, event handling or AJAX. But KO can parse data from AJAX calls. KO’s focus: design scalable, data-driven UI.

Chapter 1 – Conceptual Overview

KO use M.V.V.M, which is a variant of MVC model.

Comparison
MVC’s Model –> MVVM’s Model
MVC’s View –> MVVM’s View
MVC’s Controller –> MVVM’s ViewModel

ViewModel is a javascript representation of the model data along with associated functions for manipulating the data.

KO creates a direct connection between the ViewModel and the View, which is how is can detect changes to the underlying data and automatically update the relevant aspects of the user interface.
image

Model: Business data. Typically you will save and load your model data via an AJXA call.
View: HTML/CSS. When the ViewModel changes, the view will automatically be updated.
ViewModel: Methods that interact with the Model it’s working with.

Observables

KO uses observables to track a ViewModel;s properties. Conceptually, observables are just like javascript variables. but they let KO observe their changes and automatically update the view.

image

Binding:
After you bind a view to an observable, KO is ready to displays changes to the ViewModel automatically.
image

KO includes several build-in bindings that determines how the observable appears in the UI. Most simple: simply display the value of the observable.

Chapter 2 – Hello, Knockout.js

High level survey of KO;main components – VM, View, Obs, Binding – how they interact.

First create a simple HTML page to hold all our code. Download Knockout.js – you did this. 

Page 14, 01/16/2013, 09:52pm

Create a local site, and add an index.html
image

Download the style.css file from https://bitbucket.org/syncfusion/knockoutjs_succinctly
Make sure the CSS/JS files are loaded correctly using Fiddler2.

We’re creating a shopping cart. First, define the ViewModel. we can skip model and go to VM directly.
image

A VM is a pure javascript representation of your model data. To start out, we will just use a native javascript object as our VM. Add this code under the knockout.js include script.
image

This creates a “person” named bruce chao; and the ko.applyBinding() method tells KO to use the object as the ViewModel for the page. But we need to bind HTML element to the personViewModel.

Binding an HTML Element

KO uses a special data-bind attribute to bind HTML elements to the VM. Change the index.html so the shopper’s name is a <span> tag
image

You get this:
image
The value of the data-bind attribute tells KO what to display in the element.

If you update the property after applyBinding, the HTML still will not change because the properties 9first name, last name) are not observables.
image

If you want KO to track the changes for you, the firstname and lastname must be a KO observable. (called AUTOMATIC DEPENDENCY TRACKER)  So do this:
image

**** Note you need to use personViewModel.firstname(‘Magugu’) to set the value to keep the “tracking”; if you use personViewModel.firstname=’Magugu’, it will not track the change  for you.

Then you will see this:
image
(first name changed to [Magugu] even after you applyBinding())

Observables are actually functions, not variables
Getting observable: obj.firstname()
Setting observable: obj.firstname(‘Mary’)

Using Custom Objects

Now we define the data as a javascript class:
image

You get:
image

Interactive Bindings

Add a checkout button to call the checkout function.
image

instead of text binding the value of a property, the click binding calls a method of the ViewModel bound to the page.
image

Chapter 3 – Observables

Page 22, 01/17/2013, 00:37am

KO comes with 2 mores ways of exposing VM properties:
(1) computed observables
(2) observable arrays

Computed Observables
image
Computed observables let you create properties that are dynamically generated. (such as sku + ‘ – ‘ + description). You can combine several normal observables into a single property, KO will keep the view up to date.

Observable Arrays
Combines KO’s observable with native JavaScript array. 
image

Computed Observables

In the index.html, create the fullName computed observable.
image
You will see:
image

function () {….} is an anonymous function
pass this function to ko.computed() to make it an observable.

The HTML will be updated even if you make changes after the bindings (because it’s an observable)
image

Observable Arrays

Observable arrays let KO track list of items. We will crate a shopping cart. First create a custom object to represent object. Ass this javascript function. It accepts two parameters and create a Product, and both fields are tracked.
image

It’s possible to give multiple observable properties, and KO will manage all of the interdependencies. So it’s possible to create relationships between multiple models.

Now we’re creating some products and add them to shopping cart. (use ko.observableArray to create the products)
image

Then Bind this array to the HTML table!
image

use tbody to bind tot eh observable array!!!!!!!
Then you get this plain table:
image

Now we want to define a method that add a new product to the observableArray.
image

Then we create a button to call the method.
image

Ko always makes the minimal amount of changes to sync the UI.

Deleting Items

Define a removeProduct() function
image

Add a button to each row. Click: will invoke the removeProduct method.
image
When you’re calling the VM’s method within the foreach loop, use $root.{Method name}

KO automatically use the current item in the loop as the parameter to removeProduct.

You will see:
image
Clicking the button will remove the item immediately. KO at work!!!

Destroying Items

remove( ) is helpful, but might be troublesome if you’re sending data from VM to server side code. You either have the send the entire list to the server, or need to decide which one has been changed. To resolve this issue, KO has destroy(). Change removeProduct to this:

image

the deleted product will be removed from HTML, but will still be in the list. The only thing that changes is that the –destroy property will be set to true. Later you can send a list of products with _destroy = true t the server. So _destroy is similar to “mark deleted”. Efficient way to work with AJAX.

Ko defines its own push/pop/shift/sort methods. It’s a better idea to us KO’s version because KO will automatically update dependent view components.
push()
pop()
unshift()
shift()
slice()
remove()
removeAll()
destroy()
destroyAll()
sort()
reversed()
indexOf()

Page 30, 01/17/2013, 11:24pm


 

 

 

 


 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s