HTML and CSS Reference
In-Depth Information
Because the server doesn't have any concept of observables, it will just supply a plain
JavaScript object (usually serialized as JSON).
You could manually bind this viewModel to some HTML elements as follows:
The time on the server is: <span
data-bind= 'text: serverTime' ></span>
and <span data-bind= 'text: numUsers' ></span> user(s) are
connected.
Because the viewModel properties are observable, Knockout will automatically update
the HTML elements whenever those properties change.
Next, you want to fetch the latest data from the server. For demo purposes, you might
issue an AJAX request every five seconds (perhaps using jQuery's $.getJSON or $.ajax
functions):
var data = getDataUsingAjax ();
// Gets the data from the server
The server might return JSON data similar to the following:
{
serverTime : '2010-01-07' ,
numUsers : 3
}
Finally, to update your viewModel using this data, you would write:
// Every time data is received
from the server :
viewModel . serverTime ( data . serverTime );
viewModel . numUsers ( data . numUsers );
You would have to do this for every variable you want to display on your page. If your
data structures become more complex and contain children or arrays, this becomes very
cumbersome to handle manually. However, Knockout provides facilities to easily pop‐
ulate a viewModel with an incoming JSON payload.
Alternately, you could use the Knockout.js mapping plug-in . This plug-in allows you to
create a mapping from the regular JavaScript object (or JSON structure) to an observable
viewModel . The mapping plug-in gives you a straightforward way to map that plain
JavaScript object into a viewModel with the appropriate observables. This is an alter‐
native to manually writing your own JavaScript code that constructs a viewModel based
on some data you've fetched from the server.
To create a viewModel via the mapping plug-in, replace the creation of viewModel in the
code above with the ko.mapping.fromJS function:
var viewModel =
ko . mapping . fromJS ( data );
Search WWH ::




Custom Search