To get started, include the knockoutjs script on the HTML page. Feel free to use one of the many hosted CDN versions of it.
Let’s make a couple base line assumptions. We have retrieved some JSON from an API utilizing jQuery. We will be displaying the values from the JSON into inputs in the HTML.
First, we need to setup our HTML that we will be filling in. We will be creating a simple form to fill out name and address that looks like this.
Here is the JSON we will be using:
Now, let’s create our constructor function for the Knockout Viewmodel.
This function is taking all of the JSON properties and binding it our Viewmodel. “ko.observable” means that the value is subject to change, and should be watched for any changes. “ko.computed” means that the value is calculated from other variables and needs to watch those variables for changes. Knockout takes care of all of the observing for you and will keep all of the values up to date based off of these bindings.
Once we have our constructor setup, the knockout Viewmodel needs to be utilized in the HTML to use these values. A HTML attribute of “data-bind” is added to tie the Viewmodel to it. We want the Viewmodel to be the value attribute of the input element, so that is the handler we call. Here is what the HTML looks like with the knockout code included.
All the values inside of the inputs will be autofilled with the values passed into the createViewModel function, and everything will stay synced nicely! Once the user has updated all the inputs with new data, it is a trivial manner to extract the data from the Viewmodel and send it to the API.
This is just a brief intro into how to get started with KnockoutJS. I invite you to take a deeper dive and discover everything it can do for you.
For more information, please check out the main KnockoutJS page.