step 1: define the checkbox list frameUse a
DIVelement and set the
overflow-yCSS value to scroll. This approach will allow you to take control of your layout. For instance, you can set the height and width of your checkbox list more easily.
step 2: create a checkbox item templateDecide how you want a checkbox item in your checkbox list to look. Once decided, create the template in a
SCRIPTelement. For the sake of this example, we'll use the following HTML.
SCRIPTelement is set to
SCRIPTelement is added. The id property will be used later to reference the template.
step 3: define your view modelA view model is a key concept in the Knockout world. It helps us seperate our UI from data. The details of view model are beyond the scope of this post. Still, in the context of this example, we'll use the following view model.
This short snippet defines a basic view model that will be bound to the UI later. For your specific case, you may need to refer to the Knockout documentation.
step 4: add an observable array propertyWe want to bind to a collection of objects. The best way to handle that is by exposing a property as an
observableArray. As shown in the code snippet below, we've added an
observableArrayof objects called
step 5: add a flagExpose a flag called "isChecked" or "isSelected" on your objects. This will be used to keep the view model in sync with the user experience. This flag is even more important if you need to synchronize data between your client-side environment and a server-side environment like Node. Here's an updated version of our last snippet.
step 6: activate knockoutUse your fully defined view model and activate Knockout. First, you must initialize an instance of your view model. Then, you have to leverage Knockout's
applyBindingsmethod. These two steps are shown in the code snippet below.
step 7: define your bindingsDecorate the
DIVelement created in Step 1 with a
data-bindattribute. This attribute can be used to identify what is being bound to. Here is what our
DIVfrom step 1 looks like updated: The above snippet binds to the collection of teams completed in step 5. Each of those teams are displayed via the template created in step 2.