Knockout.js Succinctly (3)

Chapter 5 – Interactive Binding
Event Binding
Bind events to a tag
image
The VM functions:
image
Now if you add another observable: (True/False) and bind  it to a tag to toggle between True/False, and then bind it to a [visible] property of another tag, then you can achieve the effect of mouseover-show/mouseout-hide effect. 
image
image
image
You can pass extra parameter to these two functions (self.showDetails and self.hideDetails) so they can be shared by more than one tags.
To do this:
image
image

Enable/disable binding

Use to enable or disable form fields.
phone2 will be enabled only when phone 1 has a value (empty == null, so has to have something there; even a space)
image

Checked Binding
Used in checkboxes and radio buttons
Add a new observable (True/False), and a checkbox that binds to this observable.
image
Checked and observable are 1-to-1 relationship (2-way binding)
image
It’s also possible to use the [checked] to bind with (observable arrays).
image
image
image
Use [checked] in radio button
image
image

Options Binding (drop down list or multi-select list)
image
11:28am, 01/21/2013, Page 52
Using Objects as Options
If you have a list of products in an observable array, and you would like to create a drop down list from it.
image

hasfocus Binding
image

Chapter 7 – Accessing External Data
Send/Receive data using AJAX.
image
jQuery:
$.getJSON() – to get JSON data
$.post() – to post data
Now let’s get the data and use alert to see if it’s working
image

If it’s working, in the function(data), assign them to the observables!
image
Now the data is loaded:
image
POST Data:
It’s tricky to convert [observables] to JSON and send to server. Fortunately, KO has a utility function ko.toJSON().
image

Mapping Data to ViewModels
Manually mapping loaded data into observables can become quite tedious if you’re working with more than a few properties. Here comes the Mapping plug-in. Allow you automatically map JSON objects (from server) to VM observables.
Include the KO mapping library
image

Rewrite the custom javascript part – no more manually creating VM and observables, just get JSON data, and [mapping] will create a new VM based on the data – all you need to do is to bind it!!!
image
The data is loaded as soon as the page is loaded.
Page 59, 08:25pm, 01/21/2013

Advertisements

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