Building Single Page Web Apps With Sinatra: Part 2

In the first part of this mini-series, we created the basic structure of a to-do application using a Sinatra JSON interface to a SQLite database, and a Knockout-powered front-end that allows us to add tasks to our database. In this final part, we'll cover some slightly more advanced functionality in Knockout, including sorting, searching, updating, and deleting.

Let's start where we left off; here is the relevant portion of our index.erb file.


Sort

Sorting is a common task used in many applications. In our case, we want to sort the task list by any header field in our task-list table. We will start by adding the following code to the TaskViewModel:

Knockout provides a sort function for observable arrays

First, we define a sortedBy array as a property of our view model. This allows us to store if and how the collection is sorted.

Next is the sort() function. It accepts a field argument (the field we want to sort by) and checks if the tasks are sorted by the current sorting scheme. We want to sort using a "toggle" type of process. For example, sort by description once, and the tasks arrange in alphabetical order. Sort by description again, and the tasks arrange in reverse-alphabetical order. This sort() function supports this behavior by checking the most recent sort scheme and comparing it to what the user wants to sort by.

Knockout provides a sort function for observable arrays. It accepts a function as an argument that controls how the array should be sorted. This function compares two elements from the array and returns 1, 0, or -1 as a result of that comparison. All like values are grouped together (which will be useful for grouping complete and incomplete tasks together).

Note: the properties of the array elements must be called rather than simply accessed; these properties are actually functions that return the value of the property if called without any arguments.

Next, we define the bindings on the table headers in our view.

These bindings allow each of the headers to trigger a sort based on the passed string value; each of these directly maps to the Task model.


Mark As Complete

Next, we want to be able to mark a task as complete, and we'll accomplish this by simply clicking the checkbox associated with a particular task. Let's start by defining a method in the TaskViewModel:

The markAsComplete() method accepts the task as an argument, which is automatically passed by Knockout when iterating over a collection of items. We then toggle the complete property, and add a ._method="put" property to the task. This allows DataMapper to use the HTTP PUT verb as opposed to POST. We then use our convenient t.saveTask() method to save the changes to the database. Finally, we return true because returning false prevents the checkbox from changing state.

Next, we change the view by replacing the checkbox code inside the task loop with the following:

This tells us two things:

  1. The box is checked if complete is true.
  2. On click, run the markAsComplete() function from the parent (TaskViewModel in this case). This automatically passes the current task in the loop.

Deleting Tasks

To delete a task, we simply use a few convenience methods and call saveTask(). In our TaskViewModel, add the following:

This function adds a property similar to the "put" method for completing a task. The built-in destroy() method removes the passed-in task from the observable array. Finally, calling saveTask() destroys the task; that is, as long as the ._method is set to "delete".

Now we need to modify our view; add the following:

This is very similar in functionality to the complete checkbox. Note that the class="destroytask" is purely for styling purposes.


Delete All Completed

Next, we want to add the "delete all complete tasks" functionality. First, add the following code to the TaskViewModel:

This function simply iterates over the tasks to determine which of them are complete, and we call the destroyTask() method for each complete task. In our view, add the following for the "delete all complete" link.

Our click binding will work correctly, but we need to define completeTasks(). Add the following to our TaskViewModel:

This method is a computed property. These properties return a value that is computed "on the fly" when the model is updated. In this case, we return a filtered array that contains only complete tasks that are not marked for deletion. Then, we simply use this array's length property to hide or show the "Delete All Completed Tasks" link.


Incomplete Tasks Remaining

Our interface should also display the amount of incomplete tasks. Similar to our completeTasks() function above, we define an incompleteTasks() function in TaskViewModel:

We then access this computed filtered array in our view, like this:


Style Completed Tasks

We want to style the completed items differently from the tasks in the list, and we can do this in our view with Knockout's css binding. Modify the tr opening tag in our task arrayForEach() loop to the following.

This adds a complete CSS class to the table row for each task if its complete property is true.


Clean Up Dates

Let's get rid of those ugly Ruby date strings. We'll start by defining a dateFormat function in our TaskViewModel:

This function is fairly straightforward. If for any reason the date is not defined, we simply need to refresh the browser to pull in the date in the initial Task fetching function. Otherwise, we create a human readable date with the plain JavaScript Date object with the help of the MONTHS array. (Note: it is not necessary to capitalize the name of the array MONTHS, of course; this is simply a way of knowing that this is a constant value that shouldn't be changed.)

Next, we add the following changes to our view for the created_at and updated_at properties:

This passes the created_at and updated_at properties to the dateFormat() function. Once again, it's important to remember that properties of each task are not normal properties; they are functions. In order to retrieve their value, you must call the function (as shown in the above example). Note: $root is a keyword, defined by Knockout, that refers to the ViewModel. The dateFormat() method, for instance, is defined as a method of the root ViewModel (TaskViewModel).


Searching Tasks

We can search our tasks in a variety of ways, but we'll keep things simple and perform a front-end search. Keep in mind, however, that it is likely that these search results will be database driven as the data grows for the sake of pagination. But for now, let's define our search() method on TaskViewModel:

We can see that this iterates through the array of tasks and checks to see if t.query() (a regular observable value) is in the task description. Note that this check actually runs inside the setter function for the task.isvisible property. If the evaluation is false, the task isn't found and the isvisible property is set to false. If the query is equal to an empty string, all tasks are set to be visible. If the task doesn't have a description and the query is a non-empty value, the task is not a part of the returned data set and is hidden.

In our index.erb file, we set up our searching interface with the following code:

The input value is set to the ko.observable query. Next, we see that the keyup event is specifically identified as a valueUpdate event. Lastly, we set a manual event binding to keyup to execute the search (t.search()) function. No form submission is necessary; the list of matching items will display and can still be sortable, deletable, etc. Therefore, all interactions work at all times.


Final Code

index.erb

app.js

Note the rearrangement of property declarations on the TaskViewModel.


Conclusion

You now have the techniques to create more complex applications!

These two tutorials have taken you through the process of creating a single-page application with Knockout.js and Sinatra. The application can write and retrieve data, via a simple JSON interface, and it has features beyond simple CRUD actions, like mass deletion, sorting, and searching. With these tools and examples, you now have the techniques to create much more complex applications!

Tags:

Comments

Related Articles