In this blog, I will create a simple example which will demonstrate how we can use the observable features of knockout on collection of items.
Let's take a look at the code first:
In the HTML section, first up, we have two simple bindings to display the total number of courses and the total number of selected courses. Both of these are observable arrays. Then, we have a select box whose data source is allCourses. It allows for multiple selects and the multiple selections are stored in selectedCourses.
The remove button's visibility is governed by whether any courses have been selected for removal. If remove button is clicked, we simply remove the selected courses from all courses and set the selected courses to empty set.
Similarly, the sort button's visibility is governed by whether any courses exist. When sort button is clicked, we use sort as one of the many methods provided on observable arrays. The sort method takes a function which determines how sorting will work.
For adding courses, we have a form whose submit is data bound to addCourse method. This method will get called every time Add button is clicked. Add button itself is enabled only when there is a course to Add. The Add button simply adds a new course to the all courses observable array.
In this simple example, I have hard coded the entries but in a production environment these might be ajax calls to add the courses to database.
Let's take a look at the code first:
In the HTML section, first up, we have two simple bindings to display the total number of courses and the total number of selected courses. Both of these are observable arrays. Then, we have a select box whose data source is allCourses. It allows for multiple selects and the multiple selections are stored in selectedCourses.
The remove button's visibility is governed by whether any courses have been selected for removal. If remove button is clicked, we simply remove the selected courses from all courses and set the selected courses to empty set.
Similarly, the sort button's visibility is governed by whether any courses exist. When sort button is clicked, we use sort as one of the many methods provided on observable arrays. The sort method takes a function which determines how sorting will work.
For adding courses, we have a form whose submit is data bound to addCourse method. This method will get called every time Add button is clicked. Add button itself is enabled only when there is a course to Add. The Add button simply adds a new course to the all courses observable array.
In this simple example, I have hard coded the entries but in a production environment these might be ajax calls to add the courses to database.