When working with KnockoutJS, there seem to be many common operations that you need to perform on your view model objects. Internally, Knockout has a number of utility functions used by the library itself, but many of these functions might actually be handy for anyone using the library. I wanted to build a sample that highlights a few of my favorite utilities.
Handling data from the server
One of the first tasks that you typically encounter is converting data from the server to a suitable format for use in Knockout. Suppose, we are provided a JSON string from the server that was not automatically turned into a JavaScript object:
1
|
|
Knockout has a utility function ko.utils.parseJson
that will attempt to do a JSON.parse
if it is available or fall back to evaluating it as a function string for older browsers. So, we can turn our JSON string into an object like:
1
|
|
Now we have a JavaScript object, but in order to be useful in Knockout, we might need to convert some properties to observables and possibly add some computed observables. One option for doing this is Knockout’s mapping plugin. By default, it will convert all arrays into observableArrays and all other properties into observables. It also has hooks to control creation in more advanced scenarios. However, for fairly simple scenarios, it is easy enough to do the mapping yourself like:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
So, we have a constructor function for an Item, which creates our observables and adds a computed observable for showing the price with tax. We generate a mapped array of objects by using ko.utils.arrayMap
, which executes a function for each item in an array and pushes the result of the function to a new array that is returned.
Dealing with arrays in your view model
Now we have an array of items that is ready for use in Knockout. When dealing with an array though, there seem to be several common scenarios where utility functions come in handy.
Looping through an array
Suppose we want to create a computed observable at the root view model level to track the grand total for all items. We will need to sum the priceWithTax
value for all items. We could easily write a for loop to do this (or if we are using jQuery, $.each
), but Knockout provides a utility function ko.utils.arrayForEach
for this purpose. We can use this function to get our total by doing something like:
1 2 3 4 5 6 7 8 9 10 |
|
Filtering an array
Next, say we want to allow a user to filter the list of items by name. We could create a computed observable that returns the matching subset of the original array of items. Knockout’s ko.utils.arrayFilter
provides an implementation of this functionality that allows us to pass in an array and control which items are included based on the result of the function executed on each item. For example, suppose we bind a textbox to a filter observable and use it to get our filtered items:
1 2 3 4 5 6 7 8 9 10 11 |
|
We pass our array of items into ko.utils.arrayFilter
and return true only when the item’s name starts with the value of the filter observable (ko.utils.stringStartsWith
provides an easy way to do this). Now we can bind our display to filteredItems
and it will react to changes in the filter textbox. We would most likely want the display to update on each keystroke, so on our input field we can specify the binding like:
note: ko.utils.stringStartsWith
is not exported in the minified KO file`. The code is simple enough though to replicate.
1
|
|
Searching for an item in the array
Besides being able to filter the display, let’s say that we also want to be able to enter a search term and highlight the first matching entry by name. Knockout provides ko.utils.arrayFirst
that will execute a function against each item in our array and return the first item where the function evaluates to true. Similar to the filteredItems
computed observable, we can create one that returns the first match from our search field:
1 2 3 4 5 6 7 8 9 10 11 |
|
Now we can use viewModel.firstMatch
in our template to compare it against the item ($data
) that we are sending through our template and style the matching row appropriately.
Flattening an array
Suppose we needed an array that contains all of the categories currently being used in our items. Knockout’s ko.utils.arrayMap
that we used earlier is a nice way to take an array of objects and generate a flattened structure.
1 2 3 4 5 6 7 |
|
Our justCategories
computed observable now contains an array of the used categories.
Getting just the unique values in an array
While we now have a list of categories in justCategories
, what we might really want is a list of the unique categories represented in our items. Knockout’s ko.utils.arrayGetDistinctValues
takes in an array and returns an array that contains only the unique values.
1 2 3 4 |
|
Comparing two arrays
We have a list of the available categories and we have a list of the unique categories that are being used. Suppose that we want to provide a list of the categories that are missing from our data. Knockout’s ko.utils.compareArrays
provides functionality to compare two arrays and indicate which items are different. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
The result of ko.utils.compareArrays
is an array that contains items with a status
property (added
, deleted
, or retained
) and a value
property holding the original item.
Sending data back to the server
At some point, most applications will need to post data back to the server to persist changes to storage. Our view model is likely not quite in a suitable format for use on the server.
Converting our view model using ko.toJS or ko.toJSON
I hesitate to call ko.toJS
and ko.toJSON
utilities, because they seem to be a necessity as soon as you need to package up some or all of your view model for transporting it back to the server. Usually a first attempt at doing this would involve calling something like JSON.stringify(viewModel)
. After seeing the result, you are immediately reminded that observables are actually functions and that JSON does not contain functions, so the observables are ignored by JSON serializers.
Luckily, Knockout includes these helper functions to facilitate transforming all of your observables and computed observables into normal properties on a JavaScript object.
ko.toJS
– this function creates a copy of the object that you pass to it with all observables and computed observables converted into normal properties that are set to the current value.
ko.toJSON
– this function first does ko.toJS
on your object and then converts that object to a JSON string representation that is suitable for transferring back to the server. Note: this uses the browser’s native JSON.stringify()
function, which is not available in some older browsers. One way to overcome this is by referencing a script from here.
Removing properties from our converted array
We can use ko.toJS
to turn our observables into a plain object, but we may need to do some additional tweaking before it is ready to send to the server. A common scenario is that your view model contains various computed observables for display that are not expected by your server-side code. Again ko.utils.arrayMap
is useful to trim the fat off of your objects:
1 2 3 4 5 |
|
Now our items are in a proper format for posting to our server.
Knockout contains a number of utility functions that are useful for manipulating your view model. These were the ones that I find most useful. Check out the Knockout source to see all of the available utility functions.
Here is a completed sample demonstrating these utility functions: