Posted


Blog Tips Knockout

Do you use knockout? Are you fed up of repeating logic? Do you display your data in grids? Do you love a clean model? Well my friend you have come to the right place.

Displaying data in a grid is great, but most users want to be able to sort the columns how they choose, you may want to give them access to sort by header, or not. This is easy to do with an observableArray and comuptedArray within Knockout, however the logic to wire this up to a table within your site can be cumbersome, we can extract away all this logic and replace it with a simple data binding.

To achieve this, you will need the following ingredients:

Knockout

A functioning website

Some data (preferably in an array)

jQuery (Optional)

Extending knockout’s observable array

We can create a simple bubble sort that is an extension of every observable array, therefore this can be called every time we have an array.

Extending observable arrays

We unwrap the array we want to work with, if the type passed is a date then we can get the total ticks to make it easily sortable, then depending on direction of sort we tweak our logic, finally assigning the new sorted array onto the existing one. Simple, right?!

Creating a custom binding handler

Writing excess HTML and JS code can be a pain to test and maintain, we can reduce most of the duplication and make our HTML much easier to read with custom data binders. We can then render html onto the page and wire up any event that we may need. For this example, we can use our extension on the observableArray.

Creating a binding handler

Binding handlers have 2 methods

The init callback is called on each instance of the handler within the DOM, it has 2 main uses; Set any initial state of the DOM element, and register event handlers.The update callback will be called when a binding is applied to an element and every time the dependencies are changed i.e an observableArray is altered.

Passing an array to our handler means we can render some custom properties.

Option[0]: Property name we want to sort by

Option[1]: Title to display

Option[3]: Data type – optional

Using jQuery we can then create 2 html elements (one for each direction) and replace the element we are currently acting upon with the new elements.

These elements also have click events that will trigger the sort extension we created above.

Finally, once the element is clicked the “update” callback is fired toggling the visibility of each element, flipping them.

And that’s it, we can now assign this to any header of an observableArray using the “sortHtml” binding. Easy!

In Action

Using the handler is easy, we create a grid as normal, and just chuck in a sort on the column(s) we want to sort.

Using the handler

And render:

Sortable grid

Couple of renders of a sortable grid asc/desc