Data Models, functional composition and validation

While I am working my way through the Functional Javascript book I came across something that could be really useful, especially when dealing with AJAX requests.

In a nutshell you start with simple functions that do a single job and then chain them up to perform some larger task. In this example we want to validate that the json being returned from an AJAX call contains the properties we require. To do that we start with the following function:

KnockoutJS demo using Google Books API

Knockout.js

A quick and dirty demo to show off a very simple example of what you can do with some knockoutjs code and an AJAX call. I use the google books API to provide a simple search form.

JSFiddle:

Check out the jsfiddle

I also use the underscore library to work with the observableArray but that is not really a requirement. I just like it.

We start off by creating a simple html page that contains a text box, a button and a results list. In our javascript file we create a ViewModel object (function) that contains properties that match our html form. It has a field for searchInput, a function to handle searches etc. In our document ready function we apply this ViewModel to our html using ko.applyBindings(vm);. When we do this knockoutjs takes our html and resolves all the data-bind="" attributes we have added to elements and resolves them to fields on our ViewModel. This is called Model Binding and it is a powerful tool that allows us to have a single ViewModel property displayed in several places on a page, with each kept in sync to any changes. If the field we are binding to is a ko.observable then any changes made to its value will immediately show wherever it is bound.

Functional javascript using underscore

A little while ago I picked up Functional Javascript by Michael Fogus. I’m only part way through it and to be honest I should probably have waited until I finished it before starting this post but…

There is a central theme to this book which intrigued me, indeed its one of the main tenets of functional programming. It can be summed up in this quote:

“It is better to have 100 functions operate on one data structure than 10 functions on 10 data structures.” - Alan Perlis